问:
Passing Redux store in props
I'm doing an University practice building an app using React and Redux. When I start the server using Yarn, I get this error:

```<code>Passing redux store in props has been removed and does not do anything.
To use a custom Redux store for specific components, create a custom React context with React.createContext(), and pass the context object to React-Redux's Provider and specific components like:
<Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>.
You may also pass a {context : MyContext} option to connect
</code>```

My files are these:

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import ReduxProvider from './redux/ReduxProvider';
import * as serviceWorker from './serviceWorker';

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

serviceWorker.unregister();
</code>```

ReduxProvider

```<code>import { questions } from "../assets/mock-data.js";
import { Provider } from 'react-redux';
import GlobalState from "./reducers";
import { createStore } from 'redux';

import React from 'react';
import App from '../App';

export default class ReduxProvider extends React.Component {
    constructor(props) {
        super(props);
        this.initialState = {
            score: 0,
            finished: false,
            currentQuestion: 0,
            questions: [ ...questions]
        };
        this.store = this.configureStore();
    }

    render() {
        return (
            <Provider store={ this.store }>
                <div>
                    <App store={ this.store } />
                </div>
            </Provider>
        );
    }

    configureStore() {
        return createStore(GlobalState, this.initialState);
    }
}
</code>```

App.js

```<code>import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux';

class App extends Component {
  render() {
    return (
      <div className="App">
        Hola
      </div>
    );
  }
}

function mapStateToProps(state) {
    return {
      ...state
    };
}

export default connect(mapStateToProps)(App);
</code>```

reducers.js

```<code>import { combineReducers } from 'redux';

function score(state = 0, action = {}) {
    switch(action.type) {
        default:
            return state;
    }
}

function finished(state = 0, action = {}) {
    switch(action.type) {
        default:
            return state;
    }
}

function currentQuestion(state = 0, action = {}) {
    switch(action.type) {
        default:
            return state;
    }
}

function questions(state = 0, action = {}) {
    switch(action.type) {
        default:
            return state;
    }
}

const GlobalState = (combineReducers({
    score,
    finished,
    currentQuestion,
    questions
}));

export default GlobalState;
</code>```

By this time, I should be able to at least run the app without any error, but I always get that error with the Redux Store I don't know why. Could it be a problem with the version of any module or something similar?

I'm using yarn 1.12.3 and nodejs v8.12.0

Tell me if there is any other file I need to show.

答:
React Redux 7.0.1 allows passing store as a Prop again.

From the release notes:

We've brought back the ability to pass a store as a prop directly to connected components. This was removed in version 6 due to internal implementation changes (components no longer subscribed to the store directly). Some users expressed concerns that working with context in unit tests was not sufficient. Since our components use direct subscriptions again, we've reimplemented this option, and that should resolve those concerns.

Title: Passing Redux store in props

Body:
I'm doing an University practice building an app using React and Redux. When I start the server using Yarn, I get this error:

Passing redux store in props has been removed and does not do anything.
To use a custom Redux store for specific components, create a custom React context with React.createContext(), and pass the context object to React-Redux's Provider and specific components like:
<Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>.
You may also pass a {context : MyContext} option to connect

My files are these:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import ReduxProvider from './redux/ReduxProvider';
import * as serviceWorker from './serviceWorker';

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

serviceWorker.unregister();

ReduxProvider

import { questions } from "../assets/mock-data.js";
import { Provider } from 'react-redux';
import GlobalState from "./reducers";
import { createStore } from 'redux';

import React from 'react';
import App from '../App';

export default class ReduxProvider extends React.Component {
    constructor(props) {
        super(props);
        this.initialState = {
            score: 0,
            finished: false,
            currentQuestion: 0,
            questions: [ ...questions]
        };
        this.store = this.configureStore();
    }

    render() {
        return (
            <Provider store={ this.store }>

                    <App store={ this.store } />

            </Provider>
        );
    }

    configureStore() {
        return createStore(GlobalState, this.initialState);
    }
}

App.js

import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux';

class App extends Component {
  render() {
    return (

        Hola

    );
  }
}

function mapStateToProps(state) {
    return {
      ...state
    };
}

export default connect(mapStateToProps)(App);

reducers.js

import { combineReducers } from 'redux';

function score(state = 0, action = {}) {
    switch(action.type) {
        default:
            return state;
    }
}

function finished(state = 0, action = {}) {
    switch(action.type) {
        default:
            return state;
    }
}

function currentQuestion(state = 0, action = {}) {
    switch(action.type) {
        default:
            return state;
    }
}

function questions(state = 0, action = {}) {
    switch(action.type) {
        default:
            return state;
    }
}

const GlobalState = (combineReducers({
    score,
    finished,
    currentQuestion,
    questions
}));

export default GlobalState;

By this time, I should be able to at least run the app without any error, but I always get that error with the Redux Store I don't know why. Could it be a problem with the version of any module or something similar?

I'm using yarn 1.12.3 and nodejs v8.12.0

Tell me if there is any other file I need to show.


来源: stackexchange

问:
Painless: Get time difference
I am very new to Painless. I want to write a simple script to get the time difference between @timestamp and T1 in milliseconds.

I have tried using the doc['somefield'].value and doc['somefield'].date.millis and I am able to access @timestamp but not T1.

Any help will be highly appreciated! I have posted the sample data source below:

```<code>{
  "_source": {
    "@timestamp": "2018-11-06T00:20:08.802Z",
     "fields": {
      "T1": "2018-11-06T00:20:07.862Z",
    }
  }
</code>```

答:
You can define start and stop values and return the difference:

```<code>def start = doc['start_event'].date.getMillis();
def stop = doc['stop_event'].date.getMillis();
return stop - start;
</code>```

enter image description here

ContentLicense: CC BY-SA 4.0

Title: Painless: Get time difference

Body:
I am very new to Painless. I want to write a simple script to get the time difference between @timestamp and T1 in milliseconds.

I have tried using the doc['somefield'].value and doc['somefield'].date.millis and I am able to access @timestamp but not T1.

Any help will be highly appreciated! I have posted the sample data source below:

{
  "_source": {
    "@timestamp": "2018-11-06T00:20:08.802Z",
     "fields": {
      "T1": "2018-11-06T00:20:07.862Z",
    }
  }

Body:
You can define start and stop values and return the difference:

def start = doc['start_event'].date.getMillis();
def stop = doc['stop_event'].date.getMillis();
return stop - start;

enter image description here


问:
Saving DrawingVisual to an image file with a given DPI
I have got a WPF application, and I would like to save a Canvas to a file with a correct DPI value. The Canvas size is the real physical size, eg. 20x10 cm, at 300 DPI, so it's 2362x1181.

I draw images and shapes with DrawingVisual, then I create a RenderTargetBitmap. The size of the rtb is the size of the Canvas. The dpiX and dpiY are 96. I got correct image resolution only with 96 DPI. When I set it to 300, the canvas become upscale, and cropped to 2362x1181. So, it's not good. I tried to modify the canvas width and height value by dpi factor, but didn't work either.

After the RenderTargetBitmap, I use BitmapEncoder, BitmapFrame, and BinaryWriter. See code below. Working great, but the image DPI value will be 96. I've read a tons of topics about reading DPI, resaving image, using SetResolution, but I don't want to loose quality, I don't want to read file and resave it, I don't want to change pixel width/height, etc.

I just really want to save a DrawingVisual with a given DPI. I could write EXIF data for "X Resolution" (uint=282) and "Y Resoulution" (uint=283), but that didn't affect the Image DPI settings, so eg. Photoshop will read 96, not 300.

```<code>BitmapEncoder encoder = new JpegBitmapEncoder();
BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
encoder.Frames.Add(bFrame);

using (var stream = new MemoryStream())
{
encoder.Save(stream);
byte[] imageData = stream.ToArray();
using (FileStream fs = new FileStream(path, ...)
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(imageData);
bw.Close();
}
}
</code>```

答:
It seems the solution is the Bitmap SetResolution, after all. I tested it, and it looks like not affect the image quality after the JpegBitmapEncoder()! And the image resolution is untouched, keep the metadata, only the DPI will change!

Helped this documentation: https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-set-jpeg-compression-level

```<code>JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
encoder.Frames.Add(bFrame);

using (var stream = new MemoryStream())
{
    encoder.Save(stream);

    using (var bmpOutput = new System.Drawing.Bitmap(stream))
    {
        System.Drawing.Imaging.ImageCodecInfo myEncoder = GetEncoder(ImageFormat.Jpeg);

        var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
        encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

        bmpOutput.SetResolution(300.0f, 300.0f);
        bmpOutput.Save(filePath, myEncoder, encoderParameters);
    }
}
</code>```

Body:
I have got a WPF application, and I would like to save a Canvas to a file with a correct DPI value. The Canvas size is the real physical size, eg. 20x10 cm, at 300 DPI, so it's 2362x1181.

I draw images and shapes with DrawingVisual, then I create a RenderTargetBitmap. The size of the rtb is the size of the Canvas. The dpiX and dpiY are 96. I got correct image resolution only with 96 DPI. When I set it to 300, the canvas become upscale, and cropped to 2362x1181. So, it's not good. I tried to modify the canvas width and height value by dpi factor, but didn't work either.

After the RenderTargetBitmap, I use BitmapEncoder, BitmapFrame, and BinaryWriter. See code below. Working great, but the image DPI value will be 96. I've read a tons of topics about reading DPI, resaving image, using SetResolution, but I don't want to loose quality, I don't want to read file and resave it, I don't want to change pixel width/height, etc.

I just really want to save a DrawingVisual with a given DPI. I could write EXIF data for "X Resolution" (uint=282) and "Y Resoulution" (uint=283), but that didn't affect the Image DPI settings, so eg. Photoshop will read 96, not 300.

BitmapEncoder encoder = new JpegBitmapEncoder();
BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
encoder.Frames.Add(bFrame);

using (var stream = new MemoryStream())
{
encoder.Save(stream);
byte[] imageData = stream.ToArray();
using (FileStream fs = new FileStream(path, ...)
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(imageData);
bw.Close();
}
}

Body:
It seems the solution is the Bitmap SetResolution, after all. I tested it, and it looks like not affect the image quality after the JpegBitmapEncoder()! And the image resolution is untouched, keep the metadata, only the DPI will change!

Helped this documentation: https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-set-jpeg-compression-level

JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
encoder.Frames.Add(bFrame);

using (var stream = new MemoryStream())
{
    encoder.Save(stream);

    using (var bmpOutput = new System.Drawing.Bitmap(stream))
    {
        System.Drawing.Imaging.ImageCodecInfo myEncoder = GetEncoder(ImageFormat.Jpeg);

        var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
        encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

        bmpOutput.SetResolution(300.0f, 300.0f);
        bmpOutput.Save(filePath, myEncoder, encoderParameters);
    }
}


问:
Update template text with user input
I want my email template to prompt me for input, and replace specified fields with my input.

For example my email will be like:

Hello [name]

I want a box to pop up where I can enter the name and have it appear throughout the email, replacing [name].

答:
Using my example, by saving "#0#" in your template in the "to:" section of the email, by clicking this template it will prompt you to change that entry with the "Email Address" question.

Sub CommandButton1_Click()

    Call OpenTemplate

End Sub

Sub OpenTemplate()

    Dim OutMail As Outlook.MailItem
    Set OutMail = Application.CreateItemFromTemplate("Template Location")

    On Error Resume Next
    With OutMail
        .To = Replace(.To, "#0#", InputBox("Email Address"))
        .CC = ""
        .BCC = ""
        .Subject = Replace(.Subject, "#1#", InputBox("Prompt 1"))
        .Body = Replace(.Body, "#2#", InputBox("Prompt 2"))
        .Body = Replace(.Body, "#3#", InputBox("Prompt 3"))
        .Body = Replace(.Body, "#4#", InputBox("Prompt 4"))

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub
```

Title: Update template text with user input


问:
ionic4 / angular7 - How should one use the navigation API on unexpected BLE interrupts?
The code in development is running on both Android and iOS, the frameworks in use are Angular7 and ionic4 as well as the cordova BLE plugin.

After an unexpected connection failure, the app should navigate back to the root URL / home screen, which it does. But afterwards it is not possible to navigate away from the home screen and the application is stuck.

I've so far ascertained that a navigation event is indeed fired and that the underlying BLE plugin does still work and establish a new connection when trying to reconnect.

According to the Google Chrome developer tools, the DOM is clear of any remaining pages, as would be expected.

Also, I've ascertained that any services holding a global state are completely reset.

I've tried updating angular and ionic to the latest version, but it does not make a difference.

This code snippet is called as a callback to the (click)-Event from some s

this.communicatorService.connect(device).subscribe(
            peripheral => {
                console.debug('CONNECTED');
                this.zone.run(() => {
                    this.navCtrl.navigateForward('/connected').then(
                        _ => console.debug('NAVIGATED')
                    );
                });
            },
            error => {
                console.error(error);
                this.resetState();
                this.zone.run(() => {
                    this.navCtrl.navigateBack('/').then(
                        _ => console.debug('NAVIGATED BACK')
                    )
                });
            }
        );
```

What I expect would be to read CONNECTED and NAVIGATED on the console and then witness a page transition.

This is only the case before the app experiences an unexpected BLE connection loss.

After a connection loss I can read 'NAVIGATED BACK' on the console. When trying to reconnect to the BLE device, the code-snippet is executed and I can read CONNECTED and NAVIGATED, but no page transition occurs.

Am I using the navigation API correctly in this case?

答: Found the error. I had a blocking statement in a controller's ngOnDestroy-method.</p>

Body:
The code in development is running on both Android and iOS, the frameworks in use are Angular7 and ionic4 as well as the cordova BLE plugin.

After an unexpected connection failure, the app should navigate back to the root URL / home screen, which it does. But afterwards it is not possible to navigate away from the home screen and the application is stuck.

I've so far ascertained that a navigation event is indeed fired and that the underlying BLE plugin does still work and establish a new connection when trying to reconnect.

According to the Google Chrome developer tools, the DOM is clear of any remaining pages, as would be expected.

Also, I've ascertained that any services holding a global state are completely reset.

I've tried updating angular and ionic to the latest version, but it does not make a difference.

This code snippet is called as a callback to the (click)-Event from some s

this.communicatorService.connect(device).subscribe(
            peripheral => {
                console.debug('CONNECTED');
                this.zone.run(() => {
                    this.navCtrl.navigateForward('/connected').then(
                        _ => console.debug('NAVIGATED')
                    );
                });
            },
            error => {
                console.error(error);
                this.resetState();
                this.zone.run(() => {
                    this.navCtrl.navigateBack('/').then(
                        _ => console.debug('NAVIGATED BACK')
                    )
                });
            }
        );

What I expect would be to read CONNECTED and NAVIGATED on the console and then witness a page transition.

This is only the case before the app experiences an unexpected BLE connection loss.

After a connection loss I can read 'NAVIGATED BACK' on the console. When trying to reconnect to the BLE device, the code-snippet is executed and I can read CONNECTED and NAVIGATED, but no page transition occurs.

Am I using the navigation API correctly in this case?


问:
how to combine Isin , contains ,with case sensitive while filtering data
I have a data frame and I have multiple conditions to filter that data
for ex:

```<code>state =  Andhra Pradesh, Uttar Pradesh, Madya Pradesh, Karnataka, Telangana
</code>```

and

```<code>field_id = 23234,23235,34342,34343...

 Input:
 --------
field_id,state,latitude,longitude
23234,Uttar Pradesh,28.05990445,78.34249247
23235,Uttar Pradesh,27.6206712,78.7132515
23236,Uttar Pradesh,27.95378227,79.04653615
23237,Uttar Pradesh,28.63232205,78.5763061
34342,Telangana,18.71517059,78.70715893
34343,Telangana,18.11666882,79.3873906
34344,Telangana,18.4527501,79.21027678
45452,Madhya Pradesh,21.70770808,75.67139279
45453,Madhya Pradesh,21.75613982,76.29656126
45454,Madhya Pradesh,22.05077277,79.2375098
56562,Karnataka,12.38318394,76.02965431
56563,Karnataka,12.38297092,76.02957524
56564,Karnataka,14.26369026,75.43180631
67672,Andhra Pradesh,16.83612945,80.99260486
67673,Andhra Pradesh,16.83277887,80.99537748
67674,Andhra Pradesh,16.83311322,80.99560818
</code>```

I tried

```<code>state = Andhra Pradesh,Madhya Pradesh,Karnataka
State1 = State.split(',')
dsna = dsna.loc[dsna['State'].isin(State1)]
</code>```

Which works with exact match case

```<code>field_id = 23234,34345
field_id1 = field_id.split(',')
dsna = dsna.loc[dsna['field_id'].isin(field_id1)]
</code>```

Here also filters exact data frame

here dsna is my dataframe i will attach csv of that data frame or table

```<code>dsna = dsna.loc[dsna['field_id'].isin(field_id1)]
dsna = dsna.loc[dsna['State'].isin(State1)]
</code>```

I wanted filter data based on regex format
like state = pradesh,telangana ( i gave lower case)
it should filter all data related to those states and list down latitude and longitude
similar way field_id= 232,343,454 should filter all fields reated to data expecting data should relate to the regex and case sensitive and filter multiple values any pandas functionality helps to do that Since my data already in data frame

答:
By using Pandas

```<code>dsna = dsna[dsna['State'].str.contains('|'.join(State),
                                                     case=False)]
</code>```

I used | to search throughout Strings.

Body:
I have a data frame and I have multiple conditions to filter that data
for ex:

state =  Andhra Pradesh, Uttar Pradesh, Madya Pradesh, Karnataka, Telangana

and

field_id = 23234,23235,34342,34343...

 Input:
 --------
field_id,state,latitude,longitude
23234,Uttar Pradesh,28.05990445,78.34249247
23235,Uttar Pradesh,27.6206712,78.7132515
23236,Uttar Pradesh,27.95378227,79.04653615
23237,Uttar Pradesh,28.63232205,78.5763061
34342,Telangana,18.71517059,78.70715893
34343,Telangana,18.11666882,79.3873906
34344,Telangana,18.4527501,79.21027678
45452,Madhya Pradesh,21.70770808,75.67139279
45453,Madhya Pradesh,21.75613982,76.29656126
45454,Madhya Pradesh,22.05077277,79.2375098
56562,Karnataka,12.38318394,76.02965431
56563,Karnataka,12.38297092,76.02957524
56564,Karnataka,14.26369026,75.43180631
67672,Andhra Pradesh,16.83612945,80.99260486
67673,Andhra Pradesh,16.83277887,80.99537748
67674,Andhra Pradesh,16.83311322,80.99560818

I tried

state = Andhra Pradesh,Madhya Pradesh,Karnataka
State1 = State.split(',')
dsna = dsna.loc[dsna['State'].isin(State1)]

Which works with exact match case

field_id = 23234,34345
field_id1 = field_id.split(',')
dsna = dsna.loc[dsna['field_id'].isin(field_id1)]

Here also filters exact data frame

here dsna is my dataframe i will attach csv of that data frame or table

dsna = dsna.loc[dsna['field_id'].isin(field_id1)]
dsna = dsna.loc[dsna['State'].isin(State1)]

I wanted filter data based on regex format
like state = pradesh,telangana ( i gave lower case)
it should filter all data related to those states and list down latitude and longitude
similar way field_id= 232,343,454 should filter all fields reated to data expecting data should relate to the regex and case sensitive and filter multiple values any pandas functionality helps to do that Since my data already in data frame

Body:
By using Pandas

dsna = dsna[dsna['State'].str.contains('|'.join(State),
                                                     case=False)]

I used | to search throughout Strings.


问:
How to stop table row duplications in jsf?
I am developing a jsf application with primefaces. In the application I have several tables. However whenever I refresh a page or add a new value to the table or revisit the page, the values in the table get duplicated. Now I know whats causing it. In my backing bean I use driver manager get connection in each function to establish a database connection and then I close the db connection when the function has finished. However when I refresh the page the get data function obviously gets called again and appends the values to the table. Also I know database pooling would be the best solution here but I am unable to get it to work with my application. My question is how can I prevent rows duplicating in my jsf/primefaces table and maintain a database connection so I can retrieve these values from the database? Located below is the Animal Bean class with the functions to add an animal and a function to retreive all animals from the database. NOTE: There are no duplications in the database table, just in the jsf view or jsf table

```<code>@ManagedBean(name = "animal")
@ViewScoped
public class Animal {

    public String id;
    public String breed;
    public String gender;
    public double age;
    public double weight;
    public String description;
    public String herd;
    public DataSource dataSource;
    public Connection DBConn;
    public ArrayList list = new ArrayList();

    public Animal() {

    }

    public Animal(String id, String breed, double weight, double age, String gender, String description) {
        this.id = id;
        this.breed = breed;
        this.weight = weight;
        this.age = age;
        this.gender = gender;
        this.description = description;
    }

    /**
     * Creates a new instance of herd
     *
     * @return
     */
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public double getAge() {
        return age;
    }

    public void setAge(double age) {
        this.age = age;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getHerd() {
        return herd;
    }

    public void setHerd(String herd) {
        this.herd = herd;
    }

    public String addAnimal() throws SQLException {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");

        } catch (SQLException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        }

        int insert = 0;

        FacesContext context;
        context = FacesContext.getCurrentInstance();
        ExternalContext ex = context.getExternalContext();
        int value=(int)ex.getSessionMap().get("iduser");

        PreparedStatement ps = null;

        try {

            if (DBConn != null) {
                String sql = "INSERT INTO animal(animalsTag,breed,age,weight,description,gender,farmid)VALUES(?,?,?,?,?,?,?)";
                ps = (PreparedStatement) DBConn.prepareStatement(sql);
                ps.setString(1, id);
                ps.setString(2, breed);
                ps.setDouble(3, age);
                ps.setDouble(4,weight);
                ps.setString(5, description);
                ps.setString(6, gender);
                ps.setInt(7, value);
                insert = ps.executeUpdate();
                System.out.println(insert);
                System.out.println("Data Added Successfully");
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {

                ps.close();
                DBConn.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (insert > 0) {
            return "yes";
        } else {
            return "no";
        }

    }

    public ArrayList<Animal> allAnimals() {

         try {
            Class.forName("com.mysql.jdbc.Driver");
            DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");

        } catch (SQLException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        }

        PreparedStatement ps = null;

         FacesContext context;
        context = FacesContext.getCurrentInstance();
        ExternalContext ex = context.getExternalContext();
        int value=(int)ex.getSessionMap().get("iduser");

        try {

            if (DBConn != null) {
                String sql = "Select animalsTag,breed,age,weight,description,gender FROM animal where farmid = '"
                            + value + "'";
                ps = (PreparedStatement) DBConn.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();

                if (!rs.next()) {

                    return null;
                } else {

                    rs.beforeFirst();

                    while (rs.next()) {

                        Animal animal = new Animal(
                                rs.getString("animalsTag"),
                                rs.getString("breed"),
                                rs.getDouble("age"),
                                rs.getDouble("weight"),
                                rs.getString("description"),
                                rs.getString("gender"));

                        list.add(animal);

                    }//end while

                }

            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {

                ps.close();
                DBConn.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

}
</code>```

JSF Code

```<code> <p:layout fullPage="true">

            <p:layoutUnit position="north" size="100" resizable="true" closable="true" collapsible="true">
                <div id="banner" style="float:right;">
                     <p:commandButton value="Log Out" action="#{farm.logout()}" />
                </div>
             <p:graphicImage url="/resources/images/Demeter1.png" />
            </p:layoutUnit>

            <p:layoutUnit position="south" size="100" closable="true" collapsible="true">
                Footer
            </p:layoutUnit>

            <p:layoutUnit position="west" size="175" header="Left" collapsible="true">
                <p:menu>
                    <p:submenu label="Index">
                        <p:menuitem value="Manage Farm" url="managefarm.xhtml"/>
                        <p:menuitem value="Add Paddock" url="outline.xhtml"/>
                        <p:menuitem value="Create Grass Wedge" url="grass.xhtml"/>
                        <p:menuitem value="Herd Management" url="addAnimal.xhtml"/>

                    </p:submenu>

                </p:menu>
            </p:layoutUnit>

            <p:layoutUnit position="center">
                <h1>You can see all animals on your farm here.</h1>

                <p:dataTable var="animal" value="#{animal.allAnimals()}">
                    <p:column headerText="Id">
                        <h:outputText value="#{animal.id}" />
                    </p:column>

                    <p:column headerText="Age">
                        <h:outputText value="#{animal.age}" />
                    </p:column>

                    <p:column headerText="Breed">
                        <h:outputText value="#{animal.breed}" />
                    </p:column>

                    <p:column headerText="Weight">
                        <h:outputText value="#{animal.weight}" />
                    </p:column>
                </p:dataTable>

            </p:layoutUnit>

        </p:layout>
</code>```

答:
Ced's answer to setting the components to a new object worked for me. I am using MyFaces Apache Tobago as the component framework and I had to set a new UISheet() at the top of of method for retrieving the data values for the particular table. e.g. what the value attribute of the table was bound to. This is great because I don't need to worry about separating the view scope for these :-).</p>

```<code>setTable(new UISheet()); //binding set to table attribute
if (data == null) {
// do something with data
} return data;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am developing a jsf application with primefaces. In the application I have several tables. However whenever I refresh a page or add a new value to the table or revisit the page, the values in the table get duplicated. Now I know whats causing it. In my backing bean I use driver manager get connection in each function to establish a database connection and then I close the db connection when the function has finished. However when I refresh the page the get data function obviously gets called again and appends the values to the table. Also I know database pooling would be the best solution here but I am unable to get it to work with my application. My question is how can I prevent rows duplicating in my jsf/primefaces table and maintain a database connection so I can retrieve these values from the database? Located below is the Animal Bean class with the functions to add an animal and a function to retreive all animals from the database. NOTE: There are no duplications in the database table, just in the jsf view or jsf table

@ManagedBean(name = "animal")
@ViewScoped
public class Animal {

    public String id;
    public String breed;
    public String gender;
    public double age;
    public double weight;
    public String description;
    public String herd;
    public DataSource dataSource;
    public Connection DBConn;
    public ArrayList list = new ArrayList();

    public Animal() {

    }

    public Animal(String id, String breed, double weight, double age, String gender, String description) {
        this.id = id;
        this.breed = breed;
        this.weight = weight;
        this.age = age;
        this.gender = gender;
        this.description = description;
    }

    /**
     * Creates a new instance of herd
     *
     * @return
     */
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public double getAge() {
        return age;
    }

    public void setAge(double age) {
        this.age = age;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getHerd() {
        return herd;
    }

    public void setHerd(String herd) {
        this.herd = herd;
    }

    public String addAnimal() throws SQLException {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");

        } catch (SQLException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        }

        int insert = 0;

        FacesContext context;
        context = FacesContext.getCurrentInstance();
        ExternalContext ex = context.getExternalContext();
        int value=(int)ex.getSessionMap().get("iduser");

        PreparedStatement ps = null;

        try {

            if (DBConn != null) {
                String sql = "INSERT INTO animal(animalsTag,breed,age,weight,description,gender,farmid)VALUES(?,?,?,?,?,?,?)";
                ps = (PreparedStatement) DBConn.prepareStatement(sql);
                ps.setString(1, id);
                ps.setString(2, breed);
                ps.setDouble(3, age);
                ps.setDouble(4,weight);
                ps.setString(5, description);
                ps.setString(6, gender);
                ps.setInt(7, value);
                insert = ps.executeUpdate();
                System.out.println(insert);
                System.out.println("Data Added Successfully");
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {

                ps.close();
                DBConn.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (insert > 0) {
            return "yes";
        } else {
            return "no";
        }

    }

    public ArrayList<Animal> allAnimals() {

         try {
            Class.forName("com.mysql.jdbc.Driver");
            DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");

        } catch (SQLException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
        }

        PreparedStatement ps = null;

         FacesContext context;
        context = FacesContext.getCurrentInstance();
        ExternalContext ex = context.getExternalContext();
        int value=(int)ex.getSessionMap().get("iduser");

        try {

            if (DBConn != null) {
                String sql = "Select animalsTag,breed,age,weight,description,gender FROM animal where farmid = '"
                            + value + "'";
                ps = (PreparedStatement) DBConn.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();

                if (!rs.next()) {

                    return null;
                } else {

                    rs.beforeFirst();

                    while (rs.next()) {

                        Animal animal = new Animal(
                                rs.getString("animalsTag"),
                                rs.getString("breed"),
                                rs.getDouble("age"),
                                rs.getDouble("weight"),
                                rs.getString("description"),
                                rs.getString("gender"));

                        list.add(animal);

                    }//end while

                }

            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {

                ps.close();
                DBConn.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

}

JSF Code

                Footer

You can see all animals on your farm here.

                        <h:outputText value="#{animal.id}" />

                        <h:outputText value="#{animal.age}" />

                        <h:outputText value="#{animal.breed}" />

                        <h:outputText value="#{animal.weight}" />

Body:
Ced's answer to setting the components to a new object worked for me. I am using MyFaces Apache Tobago as the component framework and I had to set a new UISheet() at the top of of method for retrieving the data values for the particular table. e.g. what the value attribute of the table was bound to. This is great because I don't need to worry about separating the view scope for these :-).

setTable(new UISheet()); //binding set to table attribute
if (data == null) {
// do something with data
} return data;


问:
Cats ValidatedNec mapN with Case Class Error Types
I'd like to use the Cats ValidatedNec data type similarly to the example in the Cats documentation for Validated in the section Meeting applicative-- in my case, I'm parsing Strings from a file, validating against an appropriate regex for the field, and then (for several fields) converting to a different data type (assuming the regex matched).  However, instead of using case objects which extend a common trait for the invalid results (as in the example), I'd like to use case classes (which extend a common trait) so I can include contextual information in the case of failure.  Can this be done as simply as calling all the validation methods (putting the results in a tuple), as in the validateForm example, and calling mapN?  I'm getting conflicting errors from Intellij (from IntelliJ, it's telling me the expected and actual parameters to mapN are the same (though it is still marking it as an error); when running sbt on the command line, it doesn't resolve the mapN method.  I'm using Scala 2.12.8 and cats 2.0.0-M1.  Any help would be appreciated!

答:
https://gist.github.com/DmytroMitin/6cf51c3563dba62307a2a256eeb4ebb5

"IntelliJ errors" are irrelevant.

Regarding "sbt errors", in order to make mapN work, check that you have

```<code>import cats.syntax.apply._
</code>```

If this still doesn't work for you provide your MCVE.

Body:
https://gist.github.com/DmytroMitin/6cf51c3563dba62307a2a256eeb4ebb5

"IntelliJ errors" are irrelevant.

Regarding "sbt errors", in order to make mapN work, check that you have

import cats.syntax.apply._

If this still doesn't work for you provide your MCVE.


问:
React Native: TouchableOpacity onPress not triggering on when absolutely positioned with zIndex
I'm working on a React Native project and I'm struggling to get a TouchableOpacity to trigger it's press function when the element has the following CSS:

```<code>position: absolute;
z-index: 2;
</code>```

Below is the code:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { View } from 'react-native';

const StyledImage = styled.Image`
  height: 24px;
  width: 32px;
`;

const MenuContainer = styled.View`
  display: flex;
  position: absolute;
  background-color: #2d2d2d;
  height: ${Dimensions.get('screen').height};
  width: ${Dimensions.get('screen').width * 0.75};
  z-index: 2;
  margin-left: -8px;
  margin-top: -16px;
`;

const ProfileSectionContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-bottom: 24px;
`;

const HeadingContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 20px;
`;

const CloseButton = styled(Body1)`
  font-size: 18px;
`;

const MenuItemsContainer = styled.View`
  padding: 0 20px;
`;

const SignOutContainer = styled.View`
  position: absolute;
  bottom: 100;
  flex: 1;
  left: 40%;
`;

const handleLogout = navigate => async () => {
  await logout()
  redirectToLogin(navigate)();
};

const toggleIsOpen = (isOpen, setIsOpen) => () => setIsOpen(!isOpen);

const Menu = ({ isOpen, setIsOpen, navigate }) => (
  <MenuContainer>
    <HeadingContainer>
      <View>
        <Body1 color="#fff">New App</Body1>
      </View>
      <View>
        <TouchableOpacity onPress={toggleIsOpen(isOpen, setIsOpen)}>
          <CloseButton color="#fff">X</CloseButton>
        </TouchableOpacity>
      </View>
    </HeadingContainer>
    <ProfileSectionContainer>
      <ProfileSection />
    </ProfileSectionContainer>
    <MenuItemsContainer>
      <MenuItems menuItems={[{ text: 'Link 1' }, { text: 'Link 2' }]} />
    </MenuItemsContainer>
    <SignOutContainer>
      <TouchableOpacity onPress={handleLogout(navigate)}>
        <Body1 color="#fff">Sign Out</Body1>
      </TouchableOpacity>
    </SignOutContainer>
  </MenuContainer>
);
</code>```

I've looked at all the StackOverflow links and none of the solutions seem to work.

I'm currently on React Native 0.59.8 which is the latest at the time of writing this question.

EDIT:
The TouchableOpacity that currently isn't working is the Sign Out button which is located at the bottom of the MenuContainer. I do have another TouchableOpacity which contains the X to close the menu and that seems to work well.

答: Have you tried to add z index on TouchableOpacity? Maybe your button its behind the others components</p>

Body:
I'm working on a React Native project and I'm struggling to get a TouchableOpacity to trigger it's press function when the element has the following CSS:

position: absolute;
z-index: 2;

Below is the code:

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { View } from 'react-native';

const StyledImage = styled.Image`
  height: 24px;
  width: 32px;
`;

const MenuContainer = styled.View`
  display: flex;
  position: absolute;
  background-color: #2d2d2d;
  height: ${Dimensions.get('screen').height};
  width: ${Dimensions.get('screen').width * 0.75};
  z-index: 2;
  margin-left: -8px;
  margin-top: -16px;
`;

const ProfileSectionContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-bottom: 24px;
`;

const HeadingContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 20px;
`;

const CloseButton = styled(Body1)`
  font-size: 18px;
`;

const MenuItemsContainer = styled.View`
  padding: 0 20px;
`;

const SignOutContainer = styled.View`
  position: absolute;
  bottom: 100;
  flex: 1;
  left: 40%;
`;

const handleLogout = navigate => async () => {
  await logout()
  redirectToLogin(navigate)();
};

const toggleIsOpen = (isOpen, setIsOpen) => () => setIsOpen(!isOpen);

const Menu = ({ isOpen, setIsOpen, navigate }) => (
  <MenuContainer>
    <HeadingContainer>
      <View>
        <Body1 color="#fff">New App</Body1>
      </View>
      <View>
        <TouchableOpacity onPress={toggleIsOpen(isOpen, setIsOpen)}>
          <CloseButton color="#fff">X</CloseButton>
        </TouchableOpacity>
      </View>
    </HeadingContainer>
    <ProfileSectionContainer>
      <ProfileSection />
    </ProfileSectionContainer>
    <MenuItemsContainer>
      <MenuItems menuItems={[{ text: 'Link 1' }, { text: 'Link 2' }]} />
    </MenuItemsContainer>
    <SignOutContainer>
      <TouchableOpacity onPress={handleLogout(navigate)}>
        <Body1 color="#fff">Sign Out</Body1>
      </TouchableOpacity>
    </SignOutContainer>
  </MenuContainer>
);

I've looked at all the StackOverflow links and none of the solutions seem to work.

I'm currently on React Native 0.59.8 which is the latest at the time of writing this question.

EDIT:
The TouchableOpacity that currently isn't working is the Sign Out button which is located at the bottom of the MenuContainer. I do have another TouchableOpacity which contains the X to close the menu and that seems to work well.


问:
Is there a common Java utility to break a list into batches?
I wrote myself a utility to break a list into batches of given size. I just wanted to know if there is already any apache commons util for this.

```<code>public static <T> List<List<T>> getBatches(List<T> collection,int batchSize){
    int i = 0;
    List<List<T>> batches = new ArrayList<List<T>>();
    while(i<collection.size()){
        int nextInc = Math.min(collection.size()-i,batchSize);
        List<T> batch = collection.subList(i,i+nextInc);
        batches.add(batch);
        i = i + nextInc;
    }

    return batches;
}
</code>```

Please let me know if there any existing utility already for the same.

答:
Use Apache Commons ListUtils.partition.</p>

```<code>org.apache.commons.collections4.ListUtils.partition(final List<T> list, final int size)
</code>```

Body:
I wrote myself a utility to break a list into batches of given size. I just wanted to know if there is already any apache commons util for this.

public static <T> List<List<T>> getBatches(List<T> collection,int batchSize){
    int i = 0;
    List<List<T>> batches = new ArrayList<List<T>>();
    while(i<collection.size()){
        int nextInc = Math.min(collection.size()-i,batchSize);
        List<T> batch = collection.subList(i,i+nextInc);
        batches.add(batch);
        i = i + nextInc;
    }

    return batches;
}

Please let me know if there any existing utility already for the same.

Body:
Use Apache Commons ListUtils.partition.

org.apache.commons.collections4.ListUtils.partition(final List<T> list, final int size)


问:
generating dynamic number of checkboxes in tkinter
I'm writing some code to transfer files off of my C drive and using it as a learning exercise with tkinter. Currently I have it set up to read all the files out of my Python folder and make a checkbox for each one, and it can successfully display that list. However when you click one of the checkboxes, they all flip on or off. What part of the Checkbutton definition controls this and how would I go about changing it while still being able to generate as many checkboxes as needed? I've included the relevant code below.</p>

```<code>var = []
x = 0
while x <= 10000:
    var.append(0)
    x += 1
path = 'C:\\Users\\ebonh\\Documents\\PythonStuff'
files = []
for r, d, f in os.walk(path):
    for file in f:
        files.append(os.path.join(r, file))
Label(master, text="Transfer these files to D Drive:").grid(row=0, sticky=W)
x = 0
for f in files:
    Checkbutton(master, text=f, variable=var[x]).grid(row=(x+1), sticky=W)
    x += 1
</code>```

答:
The tkinter checkbox expects an IntVar variable, so fill your list with those:

```<code>while x <= 10000:
    var.append(IntVar(0))
    x += 1
</code>```

Then they are not checked together anymore.

Body:
I'm writing some code to transfer files off of my C drive and using it as a learning exercise with tkinter. Currently I have it set up to read all the files out of my Python folder and make a checkbox for each one, and it can successfully display that list. However when you click one of the checkboxes, they all flip on or off. What part of the Checkbutton definition controls this and how would I go about changing it while still being able to generate as many checkboxes as needed? I've included the relevant code below.

var = []
x = 0
while x <= 10000:
    var.append(0)
    x += 1
path = 'C:\\Users\\ebonh\\Documents\\PythonStuff'
files = []
for r, d, f in os.walk(path):
    for file in f:
        files.append(os.path.join(r, file))
Label(master, text="Transfer these files to D Drive:").grid(row=0, sticky=W)
x = 0
for f in files:
    Checkbutton(master, text=f, variable=var[x]).grid(row=(x+1), sticky=W)
    x += 1

Body:
The tkinter checkbox expects an IntVar variable, so fill your list with those:

while x <= 10000:
    var.append(IntVar(0))
    x += 1

Then they are not checked together anymore.


问:
How to layout UIImageView with text right to it programatically for en and ar locale?
I am trying to layout image view with label right to it. I got the layout to work in English locale, but it gives the following constraints error. It fails to render in Arabic mode, where the UIImageView is not switching its position to right.

Screenshot in English locale.

```<code>2019-05-28 17:32:09.889997+0530 App[33841:7264068] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSAutoresizingMaskLayoutConstraint:0x60000039c640 h=--& v=--& UIImageView:0x7fab2cf7c3c0.midX == 38   (active)>",
    "<NSLayoutConstraint:0x6000003a63f0 UIImageView:0x7fab2cf7c3c0.width == 38   (active)>",
    "<NSLayoutConstraint:0x6000003a6350 H:|-(0)-[UIImageView:0x7fab2cf7c3c0]   (active, names: '|':UIView:0x7fab2cf73120 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000003a63f0 UIImageView:0x7fab2cf7c3c0.width == 38   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

</code>```

```<code>// UI.swift
static func imageView(_ imageName: String) -> UIImageView {
    let iv = UIImageView(image: UIImage(named: imageName))
    iv.translatesAutoresizingMaskIntoConstraints = true
    iv.clipsToBounds = true
    return iv
}
</code>```

```<code>// ProfileViewController.swift
lazy var profileImageView: UIImageView = {
    let iv = UI.imageView("profile-placeholder")
    return iv
}()
lazy var welcomeLbl: UILabel = {
    let lbl = UI.label(text: UI.lmsg("Welcome"))
    lbl.font = UIFont(name: "Roboto", size: 16)
    return lbl
}()
lazy var nameLbl: UILabel = {
    let lbl = UI.label(text: "username placeholder")
    lbl.font = UIFont(name: "Roboto-Bold", size: 16)
    return lbl
}()
lazy var profileHeaderView: UIView = {
    let v = UI.view()
    v.translatesAutoresizingMaskIntoConstraints = false
    let lblView = UI.view()
    lblView.translatesAutoresizingMaskIntoConstraints = false
    lblView.addSubview(welcomeLbl)
    lblView.addSubview(nameLbl)
    lblView.layer.borderColor = UIColor.red.cgColor
    lblView.layer.borderWidth = 1.0
    // label view
    NSLayoutConstraint.activate([
        welcomeLbl.topAnchor.constraint(equalTo: lblView.topAnchor, constant: 0),
        welcomeLbl.leadingAnchor.constraint(equalTo: lblView.leadingAnchor, constant: 0),
        welcomeLbl.trailingAnchor.constraint(equalTo: lblView.trailingAnchor, constant: 0),
        welcomeLbl.bottomAnchor.constraint(equalTo: nameLbl.topAnchor, constant: -8)
    ])
    NSLayoutConstraint.activate([
        nameLbl.topAnchor.constraint(equalTo: welcomeLbl.bottomAnchor, constant: 8),
        nameLbl.leadingAnchor.constraint(equalTo: lblView.leadingAnchor, constant: 0),
        nameLbl.trailingAnchor.constraint(equalTo: lblView.trailingAnchor, constant: 0),
        nameLbl.bottomAnchor.constraint(equalTo: lblView.bottomAnchor, constant: 0)
    ])
    v.addSubview(profileImageView)
    v.addSubview(lblView)
    NSLayoutConstraint.activate([
        profileImageView.centerYAnchor.constraint(equalTo: v.centerYAnchor, constant: 0),
        profileImageView.leadingAnchor.constraint(equalTo: v.leadingAnchor, constant: 0),
        profileImageView.trailingAnchor.constraint(equalTo: lblView.leadingAnchor, constant: -8),
        profileImageView.widthAnchor.constraint(equalToConstant: 38)
    ])
    NSLayoutConstraint.activate([
        lblView.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor, constant: 0),
        lblView.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 8),
        lblView.trailingAnchor.constraint(equalTo: v.trailingAnchor, constant: -8)
    ])
    v.layer.borderColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)
    v.layer.borderWidth = 1.0
    return v
}()
</code>```

I am then adding the profileHeaderView in a stackView. How to fix this?

答:
It would be easier to use nested UIStackViews here so that constraints are less of an issue. What you want is something like

```<code>.____________________________.
|.________. ._______________.|
||        | |._____________.||
||        | ||Welcome      |||
||        | |'-------------'||
||        | |._____________.||
||        | ||username     |||
||        | |'-------------'||
|'--------' '---------------'|
'----------------------------'

</code>```

where the labels are in a vertical UIStackView, then that stack view and the image are in a horizontal one.

At runtime, when the user switches to a right-to-left locale, remove the image and reinsert it at the end of the outer stack view. Do the opposite when switching back to left-to-right.

The only constraints that should be needed here are the image's dimensions and the outermost stack view's position relative to its parent. The stack views' spacing and alignment properties take the place of constraints for the nested items.

Body:
I am trying to layout image view with label right to it. I got the layout to work in English locale, but it gives the following constraints error. It fails to render in Arabic mode, where the UIImageView is not switching its position to right.

Screenshot in English locale.

2019-05-28 17:32:09.889997+0530 App[33841:7264068] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSAutoresizingMaskLayoutConstraint:0x60000039c640 h=--& v=--& UIImageView:0x7fab2cf7c3c0.midX == 38   (active)>",
    "<NSLayoutConstraint:0x6000003a63f0 UIImageView:0x7fab2cf7c3c0.width == 38   (active)>",
    "<NSLayoutConstraint:0x6000003a6350 H:|-(0)-[UIImageView:0x7fab2cf7c3c0]   (active, names: '|':UIView:0x7fab2cf73120 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000003a63f0 UIImageView:0x7fab2cf7c3c0.width == 38   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

// UI.swift
static func imageView(_ imageName: String) -> UIImageView {
    let iv = UIImageView(image: UIImage(named: imageName))
    iv.translatesAutoresizingMaskIntoConstraints = true
    iv.clipsToBounds = true
    return iv
}

// ProfileViewController.swift
lazy var profileImageView: UIImageView = {
    let iv = UI.imageView("profile-placeholder")
    return iv
}()
lazy var welcomeLbl: UILabel = {
    let lbl = UI.label(text: UI.lmsg("Welcome"))
    lbl.font = UIFont(name: "Roboto", size: 16)
    return lbl
}()
lazy var nameLbl: UILabel = {
    let lbl = UI.label(text: "username placeholder")
    lbl.font = UIFont(name: "Roboto-Bold", size: 16)
    return lbl
}()
lazy var profileHeaderView: UIView = {
    let v = UI.view()
    v.translatesAutoresizingMaskIntoConstraints = false
    let lblView = UI.view()
    lblView.translatesAutoresizingMaskIntoConstraints = false
    lblView.addSubview(welcomeLbl)
    lblView.addSubview(nameLbl)
    lblView.layer.borderColor = UIColor.red.cgColor
    lblView.layer.borderWidth = 1.0
    // label view
    NSLayoutConstraint.activate([
        welcomeLbl.topAnchor.constraint(equalTo: lblView.topAnchor, constant: 0),
        welcomeLbl.leadingAnchor.constraint(equalTo: lblView.leadingAnchor, constant: 0),
        welcomeLbl.trailingAnchor.constraint(equalTo: lblView.trailingAnchor, constant: 0),
        welcomeLbl.bottomAnchor.constraint(equalTo: nameLbl.topAnchor, constant: -8)
    ])
    NSLayoutConstraint.activate([
        nameLbl.topAnchor.constraint(equalTo: welcomeLbl.bottomAnchor, constant: 8),
        nameLbl.leadingAnchor.constraint(equalTo: lblView.leadingAnchor, constant: 0),
        nameLbl.trailingAnchor.constraint(equalTo: lblView.trailingAnchor, constant: 0),
        nameLbl.bottomAnchor.constraint(equalTo: lblView.bottomAnchor, constant: 0)
    ])
    v.addSubview(profileImageView)
    v.addSubview(lblView)
    NSLayoutConstraint.activate([
        profileImageView.centerYAnchor.constraint(equalTo: v.centerYAnchor, constant: 0),
        profileImageView.leadingAnchor.constraint(equalTo: v.leadingAnchor, constant: 0),
        profileImageView.trailingAnchor.constraint(equalTo: lblView.leadingAnchor, constant: -8),
        profileImageView.widthAnchor.constraint(equalToConstant: 38)
    ])
    NSLayoutConstraint.activate([
        lblView.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor, constant: 0),
        lblView.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 8),
        lblView.trailingAnchor.constraint(equalTo: v.trailingAnchor, constant: -8)
    ])
    v.layer.borderColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)
    v.layer.borderWidth = 1.0
    return v
}()

I am then adding the profileHeaderView in a stackView. How to fix this?

Body:
It would be easier to use nested UIStackViews here so that constraints are less of an issue. What you want is something like

.____________________________.
|.________. ._______________.|
||        | |._____________.||
||        | ||Welcome      |||
||        | |'-------------'||
||        | |._____________.||
||        | ||username     |||
||        | |'-------------'||
|'--------' '---------------'|
'----------------------------'

where the labels are in a vertical UIStackView, then that stack view and the image are in a horizontal one.

At runtime, when the user switches to a right-to-left locale, remove the image and reinsert it at the end of the outer stack view. Do the opposite when switching back to left-to-right.

The only constraints that should be needed here are the image's dimensions and the outermost stack view's position relative to its parent. The stack views' spacing and alignment properties take the place of constraints for the nested items.


问:
eBay Product scraper
I am very limited on VBA,

The Code is in a Module, the code has a sub process as well, so sorry if I post the code wrong

A) open IE

B) Subprocess gets the data.

The code works fine on ebay.com but NOT for ebay.co.uk - can't work out why, also it converts urls to hyperlinks

It only does the first page, I need it to go through an X amount of pages -  have a code but can't get it to work so have removed it.

Can the search query be run AFTER Ebay opens, so it opens, then search item is input to ebay and then code runs, or to run from a cell, IF its Cell A1 the data extracted needs to be pasted in A2 and below.

I have looked at elements for ebay.com and ebay.co.uk and they look the same to me, so can't work out why its not working as it works for 1 and not the other.

I did input the code for getting data from several pages it did not work. I know this code works as I have it for when I fetch urls from google

```<code>Public IE As New SHDocVw.InternetExplorer
Sub GetData()

    Dim HTMLdoc As MSHTml.HTMLDocument
    Dim othwb As Variant
    Dim objShellWindows As New SHDocVw.ShellWindows

    Set IE = CreateObject("internetexplorer.application")

        With IE
            .Visible = True
            '.Navigate "https://www.ebay.co.uk/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=jackets&_sacat=0"
            .Navigate "https://www.ebay.com/sch/i.html_from=R40&_nkw=ralph+lauren&_sacat=1059&LH_TitleDesc=0&_dmd=1&rt=nc"
            While .Busy Or .readyState <> 4: DoEvents: Wend

Set HTMLdoc = IE.document
                ProcessHTMLPage HTMLdoc

            .Quit
        End With

End Sub
code here

    enter

'''''' THIS IS THE SUB PROCESS '''''

Sub ProcessHTMLPage(HTMLPage As MSHTml.HTMLDocument)

    Dim HTMLItem As MSHTml.IHTMLElement
    Dim HTMLItems As MSHTml.IHTMLElementCollection
    Dim HTMLInput As MSHTml.IHTMLElement
    Dim rownum As Long

    rownum = 1

    Set HTMLItems = HTMLPage.getElementsByClassName("s-item__title")

    For Each HTMLItem In HTMLItems

            Cells(rownum, 1).Value = HTMLItem.innerText
            rownum = rownum + 1

    Next HTMLItem

    rownum = 1

    Set HTMLItems = HTMLPage.getElementsByClassName("s-item__price")

    For Each HTMLItem In HTMLItems

            Cells(rownum, 2).Value = HTMLItem.innerText
            rownum = rownum + 1

    Next HTMLItem

    rownum = 1

  Set HTMLItems = HTMLPage.getElementsByClassName("s-item__link")
    For Each HTMLItem In HTMLItems
             Cells(rownum, 3).Value = HTMLItem.href
            rownum = rownum + 1

    Next HTMLItem

'Converts each text hyperlink selected into a working hyperlink from C1 to 25000 rows
  Range("C1:C25000").Select
    For Each xCell In Selection
        ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=xCell.Formula
    Next xCell
Range("C1").Select
End Sub
</code>```

Code for going to next page

```<code>pageNumber = 1
'i = 2
    If pageNumber >= 6 Then Exit Do 'the first 6 pages
    internetdata.getElementById("pnnext").click 'next web page
    Do While internet.Busy Or internet.readyState <> 4
        DoEvents
    Loop
    Set internetdata = internet.document
    pageNumber = pageNumber + 1
Loop
</code>```

Does not work on Ebay.co.uk -  NO RESULTS ARE EXTRACTED - Works fine in ebay.com

Need it to get data from X amount of pages and NOT just 1 page

Can the search query be run AFTER Ebay opens, so it opens, then search item is input to ebay and then code runs, or to run from a cell, IF its Cell A1 the data extracted needs to be pasted in A2 and below.

This is my code for google search, I have got it working so the search comes from cell A1, I am look for something like this, I am going to see if I can use the ebay code with this. As this also does the first 25 pages in google search

```<code>enter Sub webpage()

Dim ie As Object
Dim htmlDoc As Object
Dim nextPageElement As Object
Dim div As Object
Dim link As Object
Dim url As String
Dim pageNumber As Long
Dim i As Long

' Takes seach from A1 and places it into google
url = "https://www.google.co.uk/search?q=" & Replace(Worksheets("Sheet1").Range("A1").Value, " ", "+")

Set ie = CreateObject("InternetExplorer.Application")

With ie
    .Visible = True
    .navigate url
    Do While .Busy Or .readyState <> 4
        DoEvents
    Loop
End With

Application.Wait Now + TimeSerial(0, 0, 5)

Set htmlDoc = ie.document

pageNumber = 1
i = 2
Do
    For Each div In htmlDoc.getElementsByTagName("div")
        If div.getAttribute("class") = "r" Then
            Set link = div.getElementsByTagName("a")(0)
            Cells(i, 2).Value = link.getAttribute("href")
            i = i + 1
        End If
    Next div
    If pageNumber >= 25 Then Exit Do 'the first 25 pages
    Set nextPageElement = htmlDoc.getElementById("pnnext")
    If nextPageElement Is Nothing Then Exit Do

    ' Clicks web next page
    nextPageElement.Click 'next web page
    Do While ie.Busy Or ie.readyState <> 4
        DoEvents
    Loop
    Application.Wait Now + TimeSerial(0, 0, 5)
    Set htmlDoc = ie.document
    pageNumber = pageNumber + 1
Loop

MsgBox "All Done"

Set ie = Nothing
Set htmlDoc = Nothing
Set nextPageElement = Nothing
Set div = Nothing
Set link = Nothing
</code>```

End Sub
code here

答: If this works on eBay then you need to find out yourself why it's not working on ebay.co.uk. My point is if the code itself works than there is nothing we can help you with here. You need to take some time to investigate ebay.co.uk and find the differences as I am sure it's something minor. I can't help u fix code that isn't actually broken. I wish you luck though. </p>

Title: eBay Product scraper

Body:
I am very limited on VBA,

The Code is in a Module, the code has a sub process as well, so sorry if I post the code wrong

A) open IE

B) Subprocess gets the data.

The code works fine on ebay.com but NOT for ebay.co.uk - can't work out why, also it converts urls to hyperlinks

It only does the first page, I need it to go through an X amount of pages -  have a code but can't get it to work so have removed it.

Can the search query be run AFTER Ebay opens, so it opens, then search item is input to ebay and then code runs, or to run from a cell, IF its Cell A1 the data extracted needs to be pasted in A2 and below.

I have looked at elements for ebay.com and ebay.co.uk and they look the same to me, so can't work out why its not working as it works for 1 and not the other.

I did input the code for getting data from several pages it did not work. I know this code works as I have it for when I fetch urls from google

Public IE As New SHDocVw.InternetExplorer
Sub GetData()

    Dim HTMLdoc As MSHTml.HTMLDocument
    Dim othwb As Variant
    Dim objShellWindows As New SHDocVw.ShellWindows

    Set IE = CreateObject("internetexplorer.application")

        With IE
            .Visible = True
            '.Navigate "https://www.ebay.co.uk/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=jackets&_sacat=0"
            .Navigate "https://www.ebay.com/sch/i.html_from=R40&_nkw=ralph+lauren&_sacat=1059&LH_TitleDesc=0&_dmd=1&rt=nc"
            While .Busy Or .readyState <> 4: DoEvents: Wend

Set HTMLdoc = IE.document
                ProcessHTMLPage HTMLdoc

            .Quit
        End With

End Sub
code here

    enter

'''''' THIS IS THE SUB PROCESS '''''

Sub ProcessHTMLPage(HTMLPage As MSHTml.HTMLDocument)

    Dim HTMLItem As MSHTml.IHTMLElement
    Dim HTMLItems As MSHTml.IHTMLElementCollection
    Dim HTMLInput As MSHTml.IHTMLElement
    Dim rownum As Long

    rownum = 1

    Set HTMLItems = HTMLPage.getElementsByClassName("s-item__title")

    For Each HTMLItem In HTMLItems

            Cells(rownum, 1).Value = HTMLItem.innerText
            rownum = rownum + 1

    Next HTMLItem

    rownum = 1

    Set HTMLItems = HTMLPage.getElementsByClassName("s-item__price")

    For Each HTMLItem In HTMLItems

            Cells(rownum, 2).Value = HTMLItem.innerText
            rownum = rownum + 1

    Next HTMLItem

    rownum = 1

  Set HTMLItems = HTMLPage.getElementsByClassName("s-item__link")
    For Each HTMLItem In HTMLItems
             Cells(rownum, 3).Value = HTMLItem.href
            rownum = rownum + 1

    Next HTMLItem

'Converts each text hyperlink selected into a working hyperlink from C1 to 25000 rows
  Range("C1:C25000").Select
    For Each xCell In Selection
        ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=xCell.Formula
    Next xCell
Range("C1").Select
End Sub

Code for going to next page

pageNumber = 1
'i = 2
    If pageNumber >= 6 Then Exit Do 'the first 6 pages
    internetdata.getElementById("pnnext").click 'next web page
    Do While internet.Busy Or internet.readyState <> 4
        DoEvents
    Loop
    Set internetdata = internet.document
    pageNumber = pageNumber + 1
Loop

Does not work on Ebay.co.uk -  NO RESULTS ARE EXTRACTED - Works fine in ebay.com

Need it to get data from X amount of pages and NOT just 1 page

Can the search query be run AFTER Ebay opens, so it opens, then search item is input to ebay and then code runs, or to run from a cell, IF its Cell A1 the data extracted needs to be pasted in A2 and below.

This is my code for google search, I have got it working so the search comes from cell A1, I am look for something like this, I am going to see if I can use the ebay code with this. As this also does the first 25 pages in google search

enter Sub webpage()

Dim ie As Object
Dim htmlDoc As Object
Dim nextPageElement As Object
Dim div As Object
Dim link As Object
Dim url As String
Dim pageNumber As Long
Dim i As Long

' Takes seach from A1 and places it into google
url = "https://www.google.co.uk/search?q=" & Replace(Worksheets("Sheet1").Range("A1").Value, " ", "+")

Set ie = CreateObject("InternetExplorer.Application")

With ie
    .Visible = True
    .navigate url
    Do While .Busy Or .readyState <> 4
        DoEvents
    Loop
End With

Application.Wait Now + TimeSerial(0, 0, 5)

Set htmlDoc = ie.document

pageNumber = 1
i = 2
Do
    For Each div In htmlDoc.getElementsByTagName("div")
        If div.getAttribute("class") = "r" Then
            Set link = div.getElementsByTagName("a")(0)
            Cells(i, 2).Value = link.getAttribute("href")
            i = i + 1
        End If
    Next div
    If pageNumber >= 25 Then Exit Do 'the first 25 pages
    Set nextPageElement = htmlDoc.getElementById("pnnext")
    If nextPageElement Is Nothing Then Exit Do

    ' Clicks web next page
    nextPageElement.Click 'next web page
    Do While ie.Busy Or ie.readyState <> 4
        DoEvents
    Loop
    Application.Wait Now + TimeSerial(0, 0, 5)
    Set htmlDoc = ie.document
    pageNumber = pageNumber + 1
Loop

MsgBox "All Done"

Set ie = Nothing
Set htmlDoc = Nothing
Set nextPageElement = Nothing
Set div = Nothing
Set link = Nothing

End Sub
code here


问:
Rxjs execute concatMap only once
I have two Observables, getUser and getUserAvatar.
Both of them emits two values - cached immediately using BehaviorSubject, and real after network request.

Now code works this way:

1) Send request to get user and immediately emit cached user

2)After cached user emited, code goes inside concatMap, and execute getUserAvatar first time

3)getUserAvatar send request to server and immediately emit cached userAvatar

4)Everything is completed and cached user with cached avatar returned

5) After some time, real user returned and getUser emits value again

6) At this step, I want to prevent call concatMap second time, because server request already in progress, I want just go to return 'USER LOADED.

```<code>sendGetRequest('/user/').pipe(
        concatMap(() => {
            // HERE, after user data loaded, I have url for his avatar
            return sendGetRequest('/avatar/').pipe();
        }),
        map(() => {
            return 'USER LOADED';
        })
    )
</code>```

Code for Server request

```<code>sendGetRequest(url: string, ignoreCache?: boolean): any {

    let responseSubj = new Subject();

    const cachedData = this.cache.getItemForUrl(url);
    const cacheAllowed = cachedData && !ignoreCache;
    if (cacheAllowed) {
        responseSubj = new BehaviorSubject(cachedData);
    }

    const getFromServer = this.http.get(environment.API_SERVER_URL + url, this.addAuth()).pipe(
        filter((res: any) => {

            if (cacheAllowed && JSON.stringify(cachedData) === JSON.stringify(res)) {
                responseSubj.complete();
                return false;
            }

            this.cache.setItemForUrl(url, res).then(() => {
                responseSubj.complete();
            });
            return true;
        }),
        catchError((error, caught) => {
            console.log('ERROR FROM GET REQUEST', error);
            return throwError(error);
        })
    );

    return merge(responseSubj, getFromServer);
}
</code>```

答:
So, i think this is what you are after:

https://stackblitz.com/edit/angular-2kaawf

So, as you can see, i am not declaring any Subjects to fetch the cached results. I am not saying that you should not use Subjects. You just did not need them in this case. I included a clear cache and reload button just to illustrate what you could use a subject for.

If you reload the page, you will see that the previously used data is reused. When you clear the cached however, the cached data is gone and you will see "null" after reloading.

This code will works as expected. However if you would have 2 subscriptions on the user$ observable, you will get some unexpected results. To fix those issues, look into the shareReplay operator ;)

Title: Rxjs execute concatMap only once

Body:
I have two Observables, getUser and getUserAvatar.
Both of them emits two values - cached immediately using BehaviorSubject, and real after network request.

Now code works this way:

1) Send request to get user and immediately emit cached user

2)After cached user emited, code goes inside concatMap, and execute getUserAvatar first time

3)getUserAvatar send request to server and immediately emit cached userAvatar

4)Everything is completed and cached user with cached avatar returned

5) After some time, real user returned and getUser emits value again

6) At this step, I want to prevent call concatMap second time, because server request already in progress, I want just go to return 'USER LOADED.

sendGetRequest('/user/').pipe(
        concatMap(() => {
            // HERE, after user data loaded, I have url for his avatar
            return sendGetRequest('/avatar/').pipe();
        }),
        map(() => {
            return 'USER LOADED';
        })
    )

Code for Server request

sendGetRequest(url: string, ignoreCache?: boolean): any {

    let responseSubj = new Subject();

    const cachedData = this.cache.getItemForUrl(url);
    const cacheAllowed = cachedData && !ignoreCache;
    if (cacheAllowed) {
        responseSubj = new BehaviorSubject(cachedData);
    }

    const getFromServer = this.http.get(environment.API_SERVER_URL + url, this.addAuth()).pipe(
        filter((res: any) => {

            if (cacheAllowed && JSON.stringify(cachedData) === JSON.stringify(res)) {
                responseSubj.complete();
                return false;
            }

            this.cache.setItemForUrl(url, res).then(() => {
                responseSubj.complete();
            });
            return true;
        }),
        catchError((error, caught) => {
            console.log('ERROR FROM GET REQUEST', error);
            return throwError(error);
        })
    );

    return merge(responseSubj, getFromServer);
}


问:
Install4j: adding a service icon to System tray
I created an installer through the install4j software. The installer creates & adds a service which runs in the background.

I am trying to figure if it is possible to add a System Tray icon (right bottom corner of the screen) to show that my service is running. I managed to get it working by using the following code in my main class:

```<code>            final Image image = Toolkit.getDefaultToolkit().getImage(MyClass.class.getClassLoader().getResource("funny-icon.png"));
            final TrayIcon icon = new TrayIcon(image, "Device Agent");

            if(SystemTray.isSupported())
            {
                final SystemTray tray = SystemTray.getSystemTray();
                icon.setImageAutoSize(true);

                try
                {
                    tray.add(icon);
                    ...
</code>```

The code above works only when I execute it through the IDE, not from the .exe created by the installer.

Any ideas on how to achieve that?

答: It is not possible to do so, because a service cannot access the UI. Previous Windows versions had the concept of an "interactive service" but this has been removed since Windows 7.</p>

Body:
I created an installer through the install4j software. The installer creates & adds a service which runs in the background.

I am trying to figure if it is possible to add a System Tray icon (right bottom corner of the screen) to show that my service is running. I managed to get it working by using the following code in my main class:

            final Image image = Toolkit.getDefaultToolkit().getImage(MyClass.class.getClassLoader().getResource("funny-icon.png"));
            final TrayIcon icon = new TrayIcon(image, "Device Agent");

            if(SystemTray.isSupported())
            {
                final SystemTray tray = SystemTray.getSystemTray();
                icon.setImageAutoSize(true);

                try
                {
                    tray.add(icon);
                    ...

The code above works only when I execute it through the IDE, not from the .exe created by the installer.

Any ideas on how to achieve that?


问:
Alert box needs to be closed multiple times
I'm checking the value of a form field and if the value is more than 5 an alert box pops up. This works, but I've noticed that if I fill in the field 1 time, the alert box can be closed normally. If I then enter a new value, also above 5, I need to close the alert box two times, and three times if I would enter a third value. And so on...

I read several related questions on Stackoverflow, but none seemed to be the same issue or related.

window.onload = function() {
  displayField();
};

function displayField() {
  jQuery('#groupnumber').change(function() {
    var amount5 = jQuery('#groupnumber').val();
    if (amount5 > 5) {
      alert('Alert message');
    }
  });
};

//Trigger javascript on leaving field
onblur = "displayField();"
```

So it "keeps score". If I enter a different value the second time and it is still above 5, I would like the alert box to just show once.

Thanks for any help!

答:
You can wrap your window.onload function with setTimeout so user have enough time to enter their number

window.onload = function() {
setTimeout(function(){
  displayField();
  }, 2000)
};

function displayField() {
  jQuery('#groupnumber').change(function() {
    var amount5 = jQuery('#groupnumber').val();
    if (amount5 > 5) {
      alert('Alert message');
    }
  });
};

//Trigger javascript on leaving field
onblur = "displayField();"```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="groupnumber" /></code>```

Body:
I'm checking the value of a form field and if the value is more than 5 an alert box pops up. This works, but I've noticed that if I fill in the field 1 time, the alert box can be closed normally. If I then enter a new value, also above 5, I need to close the alert box two times, and three times if I would enter a third value. And so on...

I read several related questions on Stackoverflow, but none seemed to be the same issue or related.

window.onload = function() {
  displayField();
};

function displayField() {
  jQuery('#groupnumber').change(function() {
    var amount5 = jQuery('#groupnumber').val();
    if (amount5 > 5) {
      alert('Alert message');
    }
  });
};

//Trigger javascript on leaving field
onblur = "displayField();"

So it "keeps score". If I enter a different value the second time and it is still above 5, I would like the alert box to just show once.

Thanks for any help!

Body:
You can wrap your window.onload function with setTimeout so user have enough time to enter their number

window.onload = function() {
setTimeout(function(){
  displayField();
  }, 2000)
};

function displayField() {
  jQuery('#groupnumber').change(function() {
    var amount5 = jQuery('#groupnumber').val();
    if (amount5 > 5) {
      alert('Alert message');
    }
  });
};

//Trigger javascript on leaving field
onblur = "displayField();"

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="groupnumber" />


问:
How to use AccessTokenTracker in Android Facebook SDK
I am using Facebook SDK 4.0

When I go to app setting and delete the permissions that I have given previously AccessTokenTracker is not called. What should I do to AccessTokenTracker be called?

I am testing the use cases of login, the following one is not tracked by AccessTokenTracker:

Someone removes your app from Facebook via app settings and revisits your app. Your app should detect this and prompt the person to log back in.

1)Go to your app and tap on the "Log in with Facebook” button

2)Tap OK to accept the read permissions (and OK again to accept write permissions where applicable)

3)Go to app settings on Facebook and remove your app

4)Repeat steps 1-2 and verify that Facebook Login works

Here is the code of my MainActivity, it is just a simple app to learn how to use the SDK.

```<code>package com.ognid.acesstokentracker;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;

public class MainActivity extends ActionBarActivity {
    CallbackManager callbackManager;
    AccessTokenTracker accessTokenTracker;
    Fragment selection=new SelectionFragment();
    Fragment login=new LoginFragment();
    String TAG=MainActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(this.getApplicationContext());
        callbackManager = CallbackManager.Factory.create();

        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(
                    AccessToken oldAccessToken,
                    AccessToken currentAccessToken) {
                Log.d(TAG,"onCurrentAccessTokenChanged");
                updateWithToken(currentAccessToken);

            }
        };
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"is tracking:"+accessTokenTracker.isTracking());

    }

    private void updateWithToken(AccessToken token) {
        if(token!=null)showFragment(selection);
        else showFragment(login);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        accessTokenTracker.stopTracking();
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        updateWithToken(AccessToken.getCurrentAccessToken());
    }

    void showFragment(Fragment f){
        getSupportFragmentManager().beginTransaction().replace(R.id.container,f).commit();
    }

}
</code>```

答:
You forgot to call </p>

```<code>accessTokenTracker.startTracking()
</code>```

<p>...FB doesn't mention it in their AccessTokenTracker documentation, but you are supposed to call that to make it work</p>

Body:
I am using Facebook SDK 4.0

When I go to app setting and delete the permissions that I have given previously AccessTokenTracker is not called. What should I do to AccessTokenTracker be called?

I am testing the use cases of login, the following one is not tracked by AccessTokenTracker:

Someone removes your app from Facebook via app settings and revisits your app. Your app should detect this and prompt the person to log back in.

1)Go to your app and tap on the "Log in with Facebook” button

2)Tap OK to accept the read permissions (and OK again to accept write permissions where applicable)

3)Go to app settings on Facebook and remove your app

4)Repeat steps 1-2 and verify that Facebook Login works

Here is the code of my MainActivity, it is just a simple app to learn how to use the SDK.

package com.ognid.acesstokentracker;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;

public class MainActivity extends ActionBarActivity {
    CallbackManager callbackManager;
    AccessTokenTracker accessTokenTracker;
    Fragment selection=new SelectionFragment();
    Fragment login=new LoginFragment();
    String TAG=MainActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(this.getApplicationContext());
        callbackManager = CallbackManager.Factory.create();

        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(
                    AccessToken oldAccessToken,
                    AccessToken currentAccessToken) {
                Log.d(TAG,"onCurrentAccessTokenChanged");
                updateWithToken(currentAccessToken);

            }
        };
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"is tracking:"+accessTokenTracker.isTracking());

    }

    private void updateWithToken(AccessToken token) {
        if(token!=null)showFragment(selection);
        else showFragment(login);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        accessTokenTracker.stopTracking();
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        updateWithToken(AccessToken.getCurrentAccessToken());
    }

    void showFragment(Fragment f){
        getSupportFragmentManager().beginTransaction().replace(R.id.container,f).commit();
    }

}

Body:
You forgot to call

accessTokenTracker.startTracking()

...FB doesn't mention it in their AccessTokenTracker documentation, but you are supposed to call that to make it work


问:
I have problem using thread passing argument
I'm trying to solve readers/writers problem using binary semaphore.

The result I expected was I'm writer2 , data is 1. I'm reader3, data is 2.

But, result is I'm writer0 , and I'm reader0 data1 , data2 ~ data5.
How can I fix my code?

```<code>int data = 0; // global variable.
void main()
{
    //other code is omitted.

    int i;
    for(i=0; i<5; i++)
            pthread_create(&w[i], NULL, writer, &i);

    for(i=0; i<20; i++)
            pthread_create(&r[i], NULL, reader, &i);

    for(i=0; i<5; i++)
            pthread_join(w[i], NULL);

    for(i=0; i<20; i++)
            pthread_join(r[i], NULL);
}
</code>```

答:
Your problem come from the parameter you pass to your thread: It will change to fast for your thread to use it.

One solution could be to create one parameter per thread:

```<code>int i;
for(i=0; i<5; i++)
{
    int *par = malloc(sizeof *par);
    *par = i;
    pthread_create(&w[i], NULL, writer, par);
}
</code>```

Warning since some memory has been allocated, it must be deallocated some where:

```<code>void * writer(void *parameter)
{
    int *par = (int*)parameter;

    /* do some operation with *par */
    printf("I'm thread %d\n", *par );

    /* free it*/
    free(par);

    .... rest of function code ...
}
</code>```

If you're confortable with memory allocation, you could just have some parameters array:

```<code>/* w array guessed from rest of code*/
thread_t w[5];
int par_w[5];
int i;
for(i=0; i<5; i++)
{
    par_w[i] = i;
    pthread_create(&w[i], NULL, writer, &par_w[i]);
}
</code>```

Body:
I'm trying to solve readers/writers problem using binary semaphore.

The result I expected was I'm writer2 , data is 1. I'm reader3, data is 2.

But, result is I'm writer0 , and I'm reader0 data1 , data2 ~ data5.
How can I fix my code?

int data = 0; // global variable.
void main()
{
    //other code is omitted.

    int i;
    for(i=0; i<5; i++)
            pthread_create(&w[i], NULL, writer, &i);

    for(i=0; i<20; i++)
            pthread_create(&r[i], NULL, reader, &i);

    for(i=0; i<5; i++)
            pthread_join(w[i], NULL);

    for(i=0; i<20; i++)
            pthread_join(r[i], NULL);
}

Body:
Your problem come from the parameter you pass to your thread: It will change to fast for your thread to use it.

One solution could be to create one parameter per thread:

int i;
for(i=0; i<5; i++)
{
    int *par = malloc(sizeof *par);
    *par = i;
    pthread_create(&w[i], NULL, writer, par);
}

Warning since some memory has been allocated, it must be deallocated some where:

void * writer(void *parameter)
{
    int *par = (int*)parameter;

    /* do some operation with *par */
    printf("I'm thread %d\n", *par );

    /* free it*/
    free(par);

    .... rest of function code ...
}

If you're confortable with memory allocation, you could just have some parameters array:

/* w array guessed from rest of code*/
thread_t w[5];
int par_w[5];
int i;
for(i=0; i<5; i++)
{
    par_w[i] = i;
    pthread_create(&w[i], NULL, writer, &par_w[i]);
}


问:
How to fetch Adwords campaign data from Google Analytics API?
Hi i am using Google Analytics API and interested in extracting the AdWords Campaigning data which is available under OverAll Traffic>>Acquisition>>Adwords>>Campaigns and my query for the same is

```<code>return service.data().ga().get(
ids='ga:' + profile_id,
start_date=start_date,
end_date=end_date,
metrics='ga:CPC,ga:transactions,ga:transactionsPerSession,ga:adCost,
ga:transactionRevenue,ga:bounceRate,ga:impressions,ga:adClicks,
ga:sessions',dimensions='ga:campaign,ga:deviceCategory',
sort ='-ga:adClicks',
segment = 'gaid::-1').execute()
</code>```

but the above query is giving me the data related to all the campaigns but i only want to fetch the data that is related to Adwords Campaigns only.So, please help me in getting this done. I guess there should be some filter or any thing else by which we can extract the desired data.

答:
```<code>auth: jwt,
ids: "ga:" + view_id,
"start-date": "YYYY-MM-DD",
"end-date": "YYYY-MM-DD",
metrics: "ga:adCost",
dimensions: "ga:campaign",
"start-index": "1",
"max-results": "1000"
</code>```

You can do something like this

Body:
Hi i am using Google Analytics API and interested in extracting the AdWords Campaigning data which is available under OverAll Traffic>>Acquisition>>Adwords>>Campaigns and my query for the same is

return service.data().ga().get(
ids='ga:' + profile_id,
start_date=start_date,
end_date=end_date,
metrics='ga:CPC,ga:transactions,ga:transactionsPerSession,ga:adCost,
ga:transactionRevenue,ga:bounceRate,ga:impressions,ga:adClicks,
ga:sessions',dimensions='ga:campaign,ga:deviceCategory',
sort ='-ga:adClicks',
segment = 'gaid::-1').execute()

but the above query is giving me the data related to all the campaigns but i only want to fetch the data that is related to Adwords Campaigns only.So, please help me in getting this done. I guess there should be some filter or any thing else by which we can extract the desired data.

Body:
auth: jwt,
ids: "ga:" + view_id,
"start-date": "YYYY-MM-DD",
"end-date": "YYYY-MM-DD",
metrics: "ga:adCost",
dimensions: "ga:campaign",
"start-index": "1",
"max-results": "1000"

You can do something like this


问:
Database flexibility and privacy, hidden structure, software compatibility and 'public' permissions
I'm one of those that recently decided to migrate from MySQL to PostgreSQL and with it a lot of old habits are being torn apart. However there is functionality from MySQL I would like to preserve in PostgreSQL.

So...  topics:

User should have ability to create tables under a restricted namespace.

Tables of one user should not be visible to other users by default (both data, structure, stored procedures and whatnot).

Optionally the user should be given the right to GRANT permissions to other users.

Default permission to new users is to have no permission (read nothing, write even less)

Maintain compatibility with applications that are not schema aware.

Point 1:

Under MySQL the solution in place was to allow the user to create databases under the criteria 'username_%'. Under PostgreSQL I thought of having one database per user such that they can create as many schemas as they want. However there is the limitation of not being able to do joins across databases, only across schemas on the same database.

The possibility of having all as PostgreSQL schemas under the same database is not completely discarded. But then it suffers from the next point...

Point 2:

After reading this question I was inclined to think that the only way to make data completely private was to use different databases. Still I can't seem to figure out how to do it and on the other hand it conflicts with the ability to do the joins mentioned in the previous point.

Point 3:

Is this even possible or do you need the 'Create roles' privilege and create a new role for the given table/schema.

Point 4:

Again, is this possible? From what I read it feels like I'm fighting the default 'public' behavior, but still I would like to have the users seeing nothing unless an admin gives them access to the information.

Point 5:

Some of the programs I use with MySQL, on which I have no direct control of the actions they perform on the database, are not schema aware. This means they simply ignore the schema layer. For this PostgreSQL provides the 'public' schema as default. However this is still a bit awkward in some cases.

It also means that by default I need one independent database per software/tool or else I need to trick the system by setting search_path to some predefined schema on a per user (role) basis.

So those are the options/solutions I've found so far. I'm fine with having to use the search_path for point 5 and sacrificing joins between tables/schemas in different databases for the sake of privacy (points 1 and 2), but I would still like to know what is the best solution to the above problems and what are the best ways to put them in practice.

With that said, I'm all ears.

PS: Links to information on how to accomplish the mentioned above are also welcome.

答:
The solution we ended up taking is the following:

Point 1:

One database per user. User can create as many tables and schema as he wants. Joins across databases are not possible. The alternative is to retrieve subsets and manage the results on the client, obviously not the most efficient way.

Point 2:

This can be accomplished by defining a specific ownership and permission for a given database and removing the default "public" behavior. With this, only users that belong to allowed groups or are the owner itself can access the content.

Note: PostgreSQL uses multiple level permissions which means that even if the database is owned by someone, tables can be owned by someone else.

Point 3:

Can be done with WITH GRANT OPTION.

Point 4:

There is no automated way to do this. The only way to ensure this is by restricting "public" access to all existing databases.

Point 5:

Using search_path on a per user basis is the only way to do it, using multiple users to access different schema (when needed). There is obviously the issue that a schema unaware application cannot "reach" other schema if no user with appropriate search_path exists.

ContentLicense: CC BY-SA 2.5