问:
How to display actual window size (width and height) automatically?
I have a simple code, which by clicking shows the actual size of window (width and height) but I want to do this without clicking, for example when I change the size of window i want to changed the size automatically and displayed.
thanks.</p>

```<code><!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">show the window size</button>
<p id="demo"></p>
<script>
function myFunction() {
    var w = window.innerWidth;
    var h = window.innerHeight;
    document.getElementById("demo").innerHTML = "Width: " + w + "<br>Height: " + h;
}
</script>
</body>
</html>
</code>```

答:
Since you tagged jQuery in this post, I'm going to assume you use it in your page.

Ideally, you don't want to fire your function every time the window resize event is fired, but after the resize completes. This involves the use of a debounce function...

There are multiple implementations out there in the world (for example, the debounce from underscore.js) but here's a simple implementation that should do the trick:

```<code>var resizeTimer;
$(window).on('resize', function(e) {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {
    myFunction(); // call your function
  }, 250); // in this case 250 milliseconds between events is required
})
.resize(); // call the resize event on page load to get your initial values
</code>```

Body:
I have a simple code, which by clicking shows the actual size of window (width and height) but I want to do this without clicking, for example when I change the size of window i want to changed the size automatically and displayed.
thanks.

<!DOCTYPE html>

<button onclick="myFunction()">show the window size</button>

Body:
Since you tagged jQuery in this post, I'm going to assume you use it in your page.

Ideally, you don't want to fire your function every time the window resize event is fired, but after the resize completes. This involves the use of a debounce function...

There are multiple implementations out there in the world (for example, the debounce from underscore.js) but here's a simple implementation that should do the trick:

var resizeTimer;
$(window).on('resize', function(e) {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {
    myFunction(); // call your function
  }, 250); // in this case 250 milliseconds between events is required
})
.resize(); // call the resize event on page load to get your initial values


来源: stackexchange

问:
How to create or show scroll up
How do I create a button to scroll up
I see it in a lot of applications
I hope to get some help and also put some examples
Thank you</p>

答:
Depends on what you are using. You will need to give some extra info.

For a RecyclerView, to scroll to the top, you will do it like this:

```<code>recyclerView.getLayoutManager().scrollToPosition(0);
</code>```

If you are using a ListView:

```<code>listView.setSelectionAfterHeaderView();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to create or show scroll up

Body:
Depends on what you are using. You will need to give some extra info.

For a RecyclerView, to scroll to the top, you will do it like this:

recyclerView.getLayoutManager().scrollToPosition(0);

If you are using a ListView:

listView.setSelectionAfterHeaderView();


问:
How to force error on SwiftLint instead of warnings?
my question is very simple, how do I make all warnings become errors on SwiftLint? (without manually configuring each rule separately)

答:
To integrate SwiftLint to your project, you normally need to add a Run Script Phase, as described by the doc.

If you used the CocoaPods installation, this script would look like:

```<code>"${PODS_ROOT}/SwiftLint/swiftlint"
</code>```

That is where you can customize the command line options. In your case, you may want to use:

```<code>"${PODS_ROOT}/SwiftLint/swiftlint" lint --strict
</code>```

The warnings will still be displayed as warnings, but an extra error will be given, preventing running or archiving:

Command /bin/sh failed with exit code 3

That is the desired error.

ContentLicense: CC BY-SA 4.0

Body:
To integrate SwiftLint to your project, you normally need to add a Run Script Phase, as described by the doc.

If you used the CocoaPods installation, this script would look like:

"${PODS_ROOT}/SwiftLint/swiftlint"

That is where you can customize the command line options. In your case, you may want to use:

"${PODS_ROOT}/SwiftLint/swiftlint" lint --strict

The warnings will still be displayed as warnings, but an extra error will be given, preventing running or archiving:

Command /bin/sh failed with exit code 3

That is the desired error.


问:
i try to read integer values form txt file using eclipes but its give me some error java.lang.NumberFormatException
my code is based on gui, i try run on gui but i didnt make it.
public class SecondFrame extends JFrame {

```<code>private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                SecondFrame frame = new SecondFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public SecondFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 612, 469);
    contentPane = new JPanel();
    contentPane.setBackground(Color.BLUE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblNewLabel = new JLabel("Success !");
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 38));
    lblNewLabel.setBounds(201, 120, 233, 74);
    contentPane.add(lblNewLabel);

    JButton btnGenerateGraph = new JButton("GENERATE GRAPH");
    btnGenerateGraph.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                FileReader reader = new FileReader("rn.txt");
                BufferedReader bufferedReader = new BufferedReader(reader);

                String line;
                **here i try to convert line that i has read to integer**
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(Integer.parseInt(line));
                }
                reader.close();

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

        }
    });
    btnGenerateGraph.setFont(new Font("Tahoma", Font.BOLD, 21));
    btnGenerateGraph.setBounds(168, 221, 245, 59);
    contentPane.add(btnGenerateGraph);
}
</code>```

}

this is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "/"

my rn.txt file:

29
44
15
17

答:
After reading the line try to  replace all the new line characters or carriage returns etc and then perform Integer.parse.

text = text.replace("\n", "").replace("\r", "");

Body:
my code is based on gui, i try run on gui but i didnt make it.
public class SecondFrame extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                SecondFrame frame = new SecondFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public SecondFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 612, 469);
    contentPane = new JPanel();
    contentPane.setBackground(Color.BLUE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblNewLabel = new JLabel("Success !");
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 38));
    lblNewLabel.setBounds(201, 120, 233, 74);
    contentPane.add(lblNewLabel);

    JButton btnGenerateGraph = new JButton("GENERATE GRAPH");
    btnGenerateGraph.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                FileReader reader = new FileReader("rn.txt");
                BufferedReader bufferedReader = new BufferedReader(reader);

                String line;
                **here i try to convert line that i has read to integer**
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(Integer.parseInt(line));
                }
                reader.close();

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

        }
    });
    btnGenerateGraph.setFont(new Font("Tahoma", Font.BOLD, 21));
    btnGenerateGraph.setBounds(168, 221, 245, 59);
    contentPane.add(btnGenerateGraph);
}

}

this is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "/"

my rn.txt file:

29
44
15
17


问:
What is the fastest way to open a form from a form?
What is the fast and effective way to open Form2 from Form1?

I work in WinCE (limited memory and CPU power) so this becomes important.

答:
The easy way:

```<code>OtherFormClass NewForm = new OtherFormClass();
NewForm.Show();
</code>```

If you can handle the memory, you can create the form in the background and popup when desired. This should give the user a nice, quick experience.

There may be other optimizations to alleviate memory pressure.

OwnerDisplayName: Gold

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
The easy way:

OtherFormClass NewForm = new OtherFormClass();
NewForm.Show();

If you can handle the memory, you can create the form in the background and popup when desired. This should give the user a nice, quick experience.

There may be other optimizations to alleviate memory pressure.

OwnerDisplayName: Michael Haren

LastEditorDisplayName: Michael Haren


问:
Might a State pattern help if I have only a few states?
If something has only two to three states, is it overkill to use the State pattern?</p>

答:
are you talking about a state-chart?

Regardless, Id say go for it.  The problem is in the future you might want to add a state, and then think its not worthwhile to implement your pattern because its just one more state, right?  And then you've got 4 states, and you have to add another, and the process repeats.

And then you get to a state (pun-intended) where you can't refactor and use the states pattern because it would involve rewriting too much code.

So, do it right the first time.


问:
Get the different name of column between 2 tables in SQL Server
In my SQL Server database, I have the same table name in different schemas. For instance schema1.card (table 1) and schema2.card (table 2).

There are around 40 tables in my database. I just want to compare both tables and want to know which are the different column names between those 2 tables.

I have attached a screenshot of the tables. I want to find out all columns which are not in table 2 but exist in table 1 and vice versa.

答:
You can use Information_schema or sys.columns

```<code>select * from information_schema.columns where table_name = 'card' and table_schema = 'schema1'
except
select * from information_schema.columns where table_name = 'card' and table_schema = 'schema2'
</code>```

--With full join

```<code>select * from information_schema.columns t1
full join information_schema.columns t2
on t1.table_catalog=t2.table_catalog
and t1.column_name = t2.column_name
where
t1.table_name = 'card' and t2.table_name = 'card'
and t1.table_schema = 'schema1' and t2.table_schema = 'schema2'
and (t1.column_name is null or t2.column_name is null)
</code>```

Body:
You can use Information_schema or sys.columns

select * from information_schema.columns where table_name = 'card' and table_schema = 'schema1'
except
select * from information_schema.columns where table_name = 'card' and table_schema = 'schema2'

--With full join

select * from information_schema.columns t1
full join information_schema.columns t2
on t1.table_catalog=t2.table_catalog
and t1.column_name = t2.column_name
where
t1.table_name = 'card' and t2.table_name = 'card'
and t1.table_schema = 'schema1' and t2.table_schema = 'schema2'
and (t1.column_name is null or t2.column_name is null)


问:
Ext JS make paging toolbar smaller
I have a very simple question but I don't seem to find a simple answer. In fact, I haven't found any answer how to make the paging toolbar of a Ext JS grid smaller.

I made a very simple fiddle to investigate how this works, and it looks like at some point ExtJS will dynamically calculate the positions of the elements in the paging toolbar. Specifically the 'left' css attributes are set.

So I would like to know how to tweak the function that calculates these values so I can decrease these values. I could use jQuery/Javascript to do this but that just sounds so wrong so I prefer a clean ExtJS way to  do this.

So instead of something like this...

I would like to see this:

For instance, the 'previous page' button in my sample has an inline css style declared (most likely done by the paging toolbar widget) with 41px to left whereas the separator icon has 81px for the same 'left' style. This goes on until the entire width of the toolbar is covered.

So to conclude, what I want is to intercept the calculations and decrease the values of the elements to lower the entire width of the toolbar.

Any suggestions would be welcome.

答:
Thought I'd post the answer to my own question. There's a config that enables horizontal scrolling when the toolbar gets too small:</p>

```<code>Ext.create('Ext.PagingToolbar', {
   overflowHandler: 'scroller'
}
</code>```

Title: Ext JS make paging toolbar smaller

Body:
Thought I'd post the answer to my own question. There's a config that enables horizontal scrolling when the toolbar gets too small:

Ext.create('Ext.PagingToolbar', {
   overflowHandler: 'scroller'
}


问:
Link not redirecting to other pages but works when directed to a division on the same page
I have a navbar and the links are not working in it. When I go to the source code (Ctrl + U) and then click on the link, it redirects me properly.

Also when I remove the JavaScript, it works but doesn’t provide the required transition.

(function() {
  [].slice.call(document.querySelectorAll('.menu')).forEach(function(menu) {
    var menuItems = menu.querySelectorAll('.menu__link'),
      setCurrent = function(ev) {
        ev.preventDefault();

        var item = ev.target.parentNode; // li

        // return if already current
        if (classie.has(item, 'menu__item--current')) {
          return false;
        }
        // remove current
        classie.remove(menu.querySelector('.menu__item--current'), 'menu__item--current');
        // set current
        classie.add(item, 'menu__item--current');
      };

    [].slice.call(menuItems).forEach(function(el) {
      el.addEventListener('click', setCurrent);
    });
  });

  [].slice.call(document.querySelectorAll('.link-copy')).forEach(function(link) {
    link.setAttribute('data-clipboard-text', location.protocol + '//' + location.host + location.pathname + '#' + link.parentNode.id);
    console.log(link);
    new Clipboard(link);
    link.addEventListener('click', function() {
      classie.add(link, 'link-copy--animate');
      setTimeout(function() {
        classie.remove(link, 'link-copy--animate');
      }, 300);
    });
  });
})(window);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section section--menu" id="Valentine">
  <nav class="menu menu--valentine" style="position: fixed; top: 0px;
    right: 10px; width: 100%; float: right; background-color: black">
    <ul class="menu__list">
      <li class="menu__item menu__item--current">Home</li>
      <li class="menu__item">Speakers</li>
      <li class="menu__item">Partners</li>
      <li class="menu__item">Blog</li>
      <li class="menu__item">Contact</li>
    </ul>
  </nav>
</section></code>```

What should I do? I’m pretty sure the error is due to the JavaScript.

答: On setCurrent you are using ev.preventDefault();. The Default event, which you are preventing, is to go to the link.

Body:
I have a navbar and the links are not working in it. When I go to the source code (Ctrl + U) and then click on the link, it redirects me properly.

Also when I remove the JavaScript, it works but doesn’t provide the required transition.

(function() {
  [].slice.call(document.querySelectorAll('.menu')).forEach(function(menu) {
    var menuItems = menu.querySelectorAll('.menu__link'),
      setCurrent = function(ev) {
        ev.preventDefault();

        var item = ev.target.parentNode; // li

        // return if already current
        if (classie.has(item, 'menu__item--current')) {
          return false;
        }
        // remove current
        classie.remove(menu.querySelector('.menu__item--current'), 'menu__item--current');
        // set current
        classie.add(item, 'menu__item--current');
      };

    [].slice.call(menuItems).forEach(function(el) {
      el.addEventListener('click', setCurrent);
    });
  });

  [].slice.call(document.querySelectorAll('.link-copy')).forEach(function(link) {
    link.setAttribute('data-clipboard-text', location.protocol + '//' + location.host + location.pathname + '#' + link.parentNode.id);
    console.log(link);
    new Clipboard(link);
    link.addEventListener('click', function() {
      classie.add(link, 'link-copy--animate');
      setTimeout(function() {
        classie.remove(link, 'link-copy--animate');
      }, 300);
    });
  });
})(window);

Home

Speakers

Partners

Blog

Contact

What should I do? I’m pretty sure the error is due to the JavaScript.


问:
Golang JSON config for routes
I have been trying to setup a JSON config file to setup dynamic routes for my application. The idea is that I will be able to setup my own URL structure depending on who is using the service. I have a struct that takes in JSON and that works fine. I am using gorilla mux.

```<code> type CustomRoute struct {
    Name string
    Method string
    Path string
    HandleFunc string
 }
</code>```

The JSON is basically identical to the struct and it goes in fine.

The issue I have is getting the HandleFunc section.

Here is the code:

```<code>func NewRouter() *mux.Router {

routerInstance := mux.NewRouter().StrictSlash(true)

    /*
    All routes from the routing table
    */

    // r = []CustomRoute with the JSON data
    r := loadRoute()
    for _, route := range r {
       var handler http.Handler

       handler = route.HandlerFunc
       handler = core.Logger(handler, route.Name)

       routerInstance.
           Methods(route.Method).
           Path(route.Path).
           Name(route.Name).
           Handler(handler)

    }

    return routerInstance
}
</code>```

I always get the following error (as one would expect)

cannot use route.HandlerFunc (type string) as type http.Handler in assignment:
          string does not implement http.Handler (missing ServeHTTP method)

I was told to use something like:

```<code>var functions = map[string]interface{}{
    "HandleFunc1": HandleFunc1,
}
</code>```

But I have no idea how to make this work

答:
I am using a mux for subdomains, so my examples may be a bit off. The map you are being told to use is done something like this:</p>

```<code>type Handlers map[string]http.HandlerFunc

func (handlers Handlers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    path := r.URL.Path
    if handle := handlers[path]; handle != nil {
        handle.ServeHTTP(w, r)
    } else {
        http.Error(w, "Not found", 404)
    }
}
</code>```

Title: Golang JSON config for routes

Body:
I have been trying to setup a JSON config file to setup dynamic routes for my application. The idea is that I will be able to setup my own URL structure depending on who is using the service. I have a struct that takes in JSON and that works fine. I am using gorilla mux.

 type CustomRoute struct {
    Name string
    Method string
    Path string
    HandleFunc string
 }

The JSON is basically identical to the struct and it goes in fine.

The issue I have is getting the HandleFunc section.

Here is the code:

func NewRouter() *mux.Router {

routerInstance := mux.NewRouter().StrictSlash(true)

    /*
    All routes from the routing table
    */

    // r = []CustomRoute with the JSON data
    r := loadRoute()
    for _, route := range r {
       var handler http.Handler

       handler = route.HandlerFunc
       handler = core.Logger(handler, route.Name)

       routerInstance.
           Methods(route.Method).
           Path(route.Path).
           Name(route.Name).
           Handler(handler)

    }

    return routerInstance
}

I always get the following error (as one would expect)

cannot use route.HandlerFunc (type string) as type http.Handler in assignment:
          string does not implement http.Handler (missing ServeHTTP method)

I was told to use something like:

var functions = map[string]interface{}{
    "HandleFunc1": HandleFunc1,
}

But I have no idea how to make this work

Body:
I am using a mux for subdomains, so my examples may be a bit off. The map you are being told to use is done something like this:

type Handlers map[string]http.HandlerFunc

func (handlers Handlers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    path := r.URL.Path
    if handle := handlers[path]; handle != nil {
        handle.ServeHTTP(w, r)
    } else {
        http.Error(w, "Not found", 404)
    }
}


问:
Database won't update in Unity Editor with Firebase
I am trying to follow the guides and help articles on Firebase's website concerning Unity's setup with the realtime database. Unfortunately I am having a hard time getting my data to sync or be added -- for some reason the database not recognizing the data I am trying to put in as a test.

Here is what I have to setup the whole thing:

```<code>public static DatabaseManager instance = null;

public string userID;
public string userDisplayName;

private DatabaseReference dbReference;

private void Awake()
{
    if (instance == null)
        instance = this;
    else if (instance != this)
        Destroy(gameObject);

    FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("URLOfAppHere");
    FirebaseApp.DefaultInstance.SetEditorP12FileName("AppFileHere.p12");
    FirebaseApp.DefaultInstance.SetEditorServiceAccountEmail("account.gserviceaccount.com");
    FirebaseApp.DefaultInstance.SetEditorP12Password("password");
    FirebaseApp.DefaultInstance.SetEditorAuthUserId("1234");

    dbReference = FirebaseDatabase.DefaultInstance.RootReference;
}

private void Start()
{

    CreateDataEntry("Testing User", "1234");
}

public void CreateDataEntry(string _displayName, string _userID)
{

    dbReference.Child("users").Child(_userID).SetValueAsync("test");
}
</code>```

My current rules set in the project are these:

```<code>{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}
</code>```

But I also tried the default one. Unfortunately, neither of which works. I then tried to set it to public but again didn't work.

Any ideas what is going here?

答:
One issue you have is that your editordatabaseurl is not specified in url form.

Check out:
https://firebase.google.com/docs/database/unity/start#configuring_the_sdk_for_the_unity_editor

It should be:

```<code>FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://YOUR-FIREBASE-APP.firebaseio.com/");
</code>```

Your service account setup also looks wrong because "account.gserviceaccount.com" is not a valid email address.  I would erase the "p12" settings you have in code and turn on public access for your database to see if that works.  Then if that works, try to follow the steps here to set up service account access.

--------------EDIT--------------------

OK I just realized you might have intentionally redacted that info.
Another gotcha with the P12 setup is that the service account you set up should have the proper permission (project editor).

...And if you set the p12 file path, Firebase will use the service account and fail even if you set public access.  so - remove any p12 values altogether and try again with public access to remove p12 configuration as a possibility.

Body:
I am trying to follow the guides and help articles on Firebase's website concerning Unity's setup with the realtime database. Unfortunately I am having a hard time getting my data to sync or be added -- for some reason the database not recognizing the data I am trying to put in as a test.

Here is what I have to setup the whole thing:

public static DatabaseManager instance = null;

public string userID;
public string userDisplayName;

private DatabaseReference dbReference;

private void Awake()
{
    if (instance == null)
        instance = this;
    else if (instance != this)
        Destroy(gameObject);

    FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("URLOfAppHere");
    FirebaseApp.DefaultInstance.SetEditorP12FileName("AppFileHere.p12");
    FirebaseApp.DefaultInstance.SetEditorServiceAccountEmail("account.gserviceaccount.com");
    FirebaseApp.DefaultInstance.SetEditorP12Password("password");
    FirebaseApp.DefaultInstance.SetEditorAuthUserId("1234");

    dbReference = FirebaseDatabase.DefaultInstance.RootReference;
}

private void Start()
{

    CreateDataEntry("Testing User", "1234");
}

public void CreateDataEntry(string _displayName, string _userID)
{

    dbReference.Child("users").Child(_userID).SetValueAsync("test");
}

My current rules set in the project are these:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

But I also tried the default one. Unfortunately, neither of which works. I then tried to set it to public but again didn't work.

Any ideas what is going here?

Body:
One issue you have is that your editordatabaseurl is not specified in url form.

Check out:
https://firebase.google.com/docs/database/unity/start#configuring_the_sdk_for_the_unity_editor

It should be:

FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://YOUR-FIREBASE-APP.firebaseio.com/");

Your service account setup also looks wrong because "account.gserviceaccount.com" is not a valid email address.  I would erase the "p12" settings you have in code and turn on public access for your database to see if that works.  Then if that works, try to follow the steps here to set up service account access.

--------------EDIT--------------------

OK I just realized you might have intentionally redacted that info.
Another gotcha with the P12 setup is that the service account you set up should have the proper permission (project editor).

...And if you set the p12 file path, Firebase will use the service account and fail even if you set public access.  so - remove any p12 values altogether and try again with public access to remove p12 configuration as a possibility.


问:
Basic use of JSONPath in Java
I have JSON as a string and a JSONPath as a string. I'd like to query the JSON with the JSON path, getting the resulting JSON as a string.

I gather that Jayway's json-path is the standard. The online API, however, doesn't have have much relation to the actual library you get from Maven. GrepCode's version roughly matches up though.

It seems like I ought to be able to do:

```<code>String originalJson; //these are initialized to actual data
String jsonPath;
String queriedJson = JsonPath.<String>read(originalJson, jsonPath);
</code>```

The problem is that read returns whatever it feels most appropriate based on what the JSONPath actually finds (e.g. a List<Object>, String, double, etc.), thus my code throws an exception for certain queries. It seems pretty reasonable to assume that there'd be some way to query JSON and get JSON back; any suggestions?

答:
Check out the jpath API. It's xpath equivalent for JSON Data. You can read data by providing the jpath which will traverse the JSON data and return the requested value.

This Java class is the implementation as well as it has example codes on how to call the APIs.

https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java

Readme -

https://github.com/satyapaul/jpath/blob/master/README.md

Title: Basic use of JSONPath in Java

Body:
I have JSON as a string and a JSONPath as a string. I'd like to query the JSON with the JSON path, getting the resulting JSON as a string.

I gather that Jayway's json-path is the standard. The online API, however, doesn't have have much relation to the actual library you get from Maven. GrepCode's version roughly matches up though.

It seems like I ought to be able to do:

String originalJson; //these are initialized to actual data
String jsonPath;
String queriedJson = JsonPath.<String>read(originalJson, jsonPath);

The problem is that read returns whatever it feels most appropriate based on what the JSONPath actually finds (e.g. a List<Object>, String, double, etc.), thus my code throws an exception for certain queries. It seems pretty reasonable to assume that there'd be some way to query JSON and get JSON back; any suggestions?


问:
How can I set different icons for visited and unvisited external links with CSS?
I'm trying to set different icons for visited and unvisited external links. At first, I tried this:

```<code>a[href^="http"] {
    padding-right: 1.1em;
    background-image: url(external_link.gif);
    background-repeat: no-repeat;
    background-position: center right;
}
a[href^="http"]:visited {
    background-image: url(visited_external_link.gif);
}
</code>```

— but, obviously, it didn't work.

This:

```<code>a {
    padding-right: 1.1em;
    background-image: url(external_link.gif);
    background-repeat: no-repeat;
    background-position: center right;
}
a:visited {
    background-image: url(visited_external_link.gif);
}
a:not([href^="http"]) {
    background-image: none;
    padding-right: 0;
}
</code>```

— didn't work too.

So, how can I to set different icons or, in other words, change icon only for visited external links? Is it possible without classes?

答:
In theory you could try using the a:visited:before or the :after selector in combination with an icon font like Font Awesome, which would look something like:

```<code>a:visited:before {
   content: "\icon-code";
}
</code>```

Or you could use your background-image:

```<code>a:visited:before {
   content: " ";
   background-image: url('your-background-image.jpg');
   height: 10px;
   width: 10px;
}
</code>```

However, beware that the :visited selectors have restrictions regarding psuedo-elements in modern browsers (to protect your privacy); for example in Firefox 4 you are only allowed to change an a:visited links' (border) colors (look here and here for reference).

Thus, as mentioned by other answers, the above will not work in production because popular browsers will not render it (per W3 school and Mozilla Developer Network).

Direct quote from the Mozilla Developer Network on the issue:

Note: For privacy reasons, browsers strictly limit the styles you can apply using an element selected by this pseudo-class: only color, background-color, border-color, border-bottom-color, border-left-color, border-right-color, border-top-color, outline-color, column-rule-color, fill and stroke. Note also that the alpha component will be ignored: the alpha component of the not-visited rule is used instead (except when the opacity is 0, in that case the whole color is ignored, and the one of the not-visited rule is used).

And you'd say that's the end of that, but it's not!
There (1) are (2) a lot (3) of interesting ways to circumvent these restrictions (for a detailed blog post with a lot of references to this issue, you can look here on CSS-tricks).

For example, one of the tricks is to style two a elements that link to the same href, and style the first one to be an icon. When someone clicks on the link with text, the a in front also gets affected.

Here's an example from the previously linked Quora post (which is based on the DuckDuckGo's visited feature) (which sadly won't work as a working snippit due to it working with links):

```<code><h2 class="result__title">
   <a class="result__a" href="https://google.com">Link to Google
   </a>
   <a class="result__check" href="https://google.com">
       <span class="result__check__tt">Link icon</span>
   </a>
</h2>
</code>```

Now in your CSS you make the .result__check only show up (in your stylesheet) if you've visited the link!

```<code>.result__check:before{
    content: "\2611";
}
.result__check {
    color: #fff;
    position: absolute;
    right: 100%;
    top: 0.3em;
    margin-right: 1em;
    font-size: 0.8em;
    width: 1em;
    white-space: nowrap;
}
.result__check:before{
    display: inline-block;
    float: right;
}
// This is what gives the color to the visited item
.result__check:visited {
    color: #c3c3c3;
}
.result__check__tt {
    visibility: hidden;
    opacity: 0;
    background-color: #a3a3a3;
    background-color: rgba(138,138,138,0.9);
    padding: 0 1em;
    font-size: 0.76em;
    line-height: 2;
    position: absolute;
    bottom: 2.5em;
    left: -0.95em;
    z-index: 200
}
.result__check__tt:before {
    content: "";
    display: block;
    position: absolute;
    margin-left: -0.5em;
    bottom: -0.5em;
    left: 1.5em;
    border: 0.5em solid transparent;
    border-bottom-width: 0;
    border-top-color: #a3a3a3;
    border-top-color: rgba(138,138,138,0.9)
}
.result__check:hover .result__check__tt {
    visibility: visible;
    opacity: 1
}
</code>```

That way, you are able to style the :visited element, even though browsers restrict it. Hope it helps!

Body:
I'm trying to set different icons for visited and unvisited external links. At first, I tried this:

a[href^="http"] {
    padding-right: 1.1em;
    background-image: url(external_link.gif);
    background-repeat: no-repeat;
    background-position: center right;
}
a[href^="http"]:visited {
    background-image: url(visited_external_link.gif);
}

— but, obviously, it didn't work.

This:

a {
    padding-right: 1.1em;
    background-image: url(external_link.gif);
    background-repeat: no-repeat;
    background-position: center right;
}
a:visited {
    background-image: url(visited_external_link.gif);
}
a:not([href^="http"]) {
    background-image: none;
    padding-right: 0;
}

— didn't work too.

So, how can I to set different icons or, in other words, change icon only for visited external links? Is it possible without classes?

Body:
In theory you could try using the a:visited:before or the :after selector in combination with an icon font like Font Awesome, which would look something like:

a:visited:before {
   content: "\icon-code";
}

Or you could use your background-image:

a:visited:before {
   content: " ";
   background-image: url('your-background-image.jpg');
   height: 10px;
   width: 10px;
}

However, beware that the :visited selectors have restrictions regarding psuedo-elements in modern browsers (to protect your privacy); for example in Firefox 4 you are only allowed to change an a:visited links' (border) colors (look here and here for reference).

Thus, as mentioned by other answers, the above will not work in production because popular browsers will not render it (per W3 school and Mozilla Developer Network).

Direct quote from the Mozilla Developer Network on the issue:

Note: For privacy reasons, browsers strictly limit the styles you can apply using an element selected by this pseudo-class: only color, background-color, border-color, border-bottom-color, border-left-color, border-right-color, border-top-color, outline-color, column-rule-color, fill and stroke. Note also that the alpha component will be ignored: the alpha component of the not-visited rule is used instead (except when the opacity is 0, in that case the whole color is ignored, and the one of the not-visited rule is used).

And you'd say that's the end of that, but it's not!
There (1) are (2) a lot (3) of interesting ways to circumvent these restrictions (for a detailed blog post with a lot of references to this issue, you can look here on CSS-tricks).

For example, one of the tricks is to style two a elements that link to the same href, and style the first one to be an icon. When someone clicks on the link with text, the a in front also gets affected.

Here's an example from the previously linked Quora post (which is based on the DuckDuckGo's visited feature) (which sadly won't work as a working snippit due to it working with links):

<h2 class="result__title">
   <a class="result__a" href="https://google.com">Link to Google
   </a>
   <a class="result__check" href="https://google.com">
       <span class="result__check__tt">Link icon</span>
   </a>
</h2>

Now in your CSS you make the .result__check only show up (in your stylesheet) if you've visited the link!

.result__check:before{
    content: "\2611";
}
.result__check {
    color: #fff;
    position: absolute;
    right: 100%;
    top: 0.3em;
    margin-right: 1em;
    font-size: 0.8em;
    width: 1em;
    white-space: nowrap;
}
.result__check:before{
    display: inline-block;
    float: right;
}
// This is what gives the color to the visited item
.result__check:visited {
    color: #c3c3c3;
}
.result__check__tt {
    visibility: hidden;
    opacity: 0;
    background-color: #a3a3a3;
    background-color: rgba(138,138,138,0.9);
    padding: 0 1em;
    font-size: 0.76em;
    line-height: 2;
    position: absolute;
    bottom: 2.5em;
    left: -0.95em;
    z-index: 200
}
.result__check__tt:before {
    content: "";
    display: block;
    position: absolute;
    margin-left: -0.5em;
    bottom: -0.5em;
    left: 1.5em;
    border: 0.5em solid transparent;
    border-bottom-width: 0;
    border-top-color: #a3a3a3;
    border-top-color: rgba(138,138,138,0.9)
}
.result__check:hover .result__check__tt {
    visibility: visible;
    opacity: 1
}

That way, you are able to style the :visited element, even though browsers restrict it. Hope it helps!


问:
Using DataBinding on custom views
I'm trying to create custom view:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <FrameLayout
        android:id="@+id/container_fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminateTint="#FFFFFF" />

    </FrameLayout>

</layout>
</code>```

And Java:

```<code>public class ImageSlideshowView extends FrameLayout {
    private ViewImageSlideshowBinding binding;

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        init(context);
    }

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context);
    }

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        init(context);
    }

    private void init(@NonNull Context context) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        binding = ViewImageSlideshowBinding.inflate(layoutInflater, this, true);
    }
}
</code>```

It works, but not correct.

If I use merge tag instead of FrameLayout without data binding, I'll get the following layout (I finally want to get this layout):

-- FrameLayout

--- ProgressBar

But I can not use merge with data binding, so with XML above I'm getting the following layout:

-- FrameLayout

--- FrameLayout

---- ProgressBar

As you can see, there is one more FrameLayout created. How to avoid it?

答:
Your custom view is a FrameLayout. And that layout contains a FrameLayout and a ProgressBar.

Try instead a layout like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <com.yourcompany.yourapp.ImageSlideshowView
        android:id="@+id/container_fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminateTint="#FFFFFF" />

    </com.yourcompany.yourapp.ImageSlideshowView>

</layout>
</code>```

Then when you include your custom view in another view you can just refer to it by its type.

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <com.yourcompany.yourapp.ParentView
        android:id="@+id/parent_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        <com.yourcompany.yourapp.ImageSlideshowView
            android:id="@+id/slideshow_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </LinearLayout>
    </com.yourcompany.yourapp.ParentView>
</layout>
</code>```

Title: Using DataBinding on custom views

Body:
I'm trying to create custom view:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <FrameLayout
        android:id="@+id/container_fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminateTint="#FFFFFF" />

    </FrameLayout>

</layout>

And Java:

public class ImageSlideshowView extends FrameLayout {
    private ViewImageSlideshowBinding binding;

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        init(context);
    }

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context);
    }

    public ImageSlideshowView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        init(context);
    }

    private void init(@NonNull Context context) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        binding = ViewImageSlideshowBinding.inflate(layoutInflater, this, true);
    }
}

It works, but not correct.

If I use merge tag instead of FrameLayout without data binding, I'll get the following layout (I finally want to get this layout):

-- FrameLayout

--- ProgressBar

But I can not use merge with data binding, so with XML above I'm getting the following layout:

-- FrameLayout

--- FrameLayout

---- ProgressBar

As you can see, there is one more FrameLayout created. How to avoid it?

Body:
Your custom view is a FrameLayout. And that layout contains a FrameLayout and a ProgressBar.

Try instead a layout like this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <com.yourcompany.yourapp.ImageSlideshowView
        android:id="@+id/container_fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminateTint="#FFFFFF" />

    </com.yourcompany.yourapp.ImageSlideshowView>

</layout>

Then when you include your custom view in another view you can just refer to it by its type.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <com.yourcompany.yourapp.ParentView
        android:id="@+id/parent_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        <com.yourcompany.yourapp.ImageSlideshowView
            android:id="@+id/slideshow_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </LinearLayout>
    </com.yourcompany.yourapp.ParentView>
</layout>


问:
How to align input forms in HTML
I'm new to HTML and I'm trying to learn how to use forms.

The biggest issue I am having so far is aligning the forms. Here is an example of my current HTML file:

```<code><form>
 First Name:<input type="text" name="first"><br />
 Last Name:<input type="text" name="last"><br />
 Email:<input type="text" name="email"><br />
</form>
</code>```

The problem with this is, the field box after 'Email' is drastically different in terms of spacing compared to first, and last name. What is the 'proper' way to make it so that they 'line-up' essentially?

I am trying to practice good form and syntax...a lot of people might do this with CSS I am not sure, I have only learned the very basics of HTML so far.

答:
A simple solution for you if you're new to HTML, is just to use a table to line everything up.

<form>

      First Name:
      <input type="text" name="first" />

      Last Name:
      <input type="text" name="last" />

      Email:
      <input type="text" name="email" />

</form>```

Title: How to align input forms in HTML

Body:
I'm new to HTML and I'm trying to learn how to use forms.

The biggest issue I am having so far is aligning the forms. Here is an example of my current HTML file:

<form>
 First Name:<input type="text" name="first">

 Last Name:<input type="text" name="last">

 Email:<input type="text" name="email">

</form>

The problem with this is, the field box after 'Email' is drastically different in terms of spacing compared to first, and last name. What is the 'proper' way to make it so that they 'line-up' essentially?

I am trying to practice good form and syntax...a lot of people might do this with CSS I am not sure, I have only learned the very basics of HTML so far.

Body:
A simple solution for you if you're new to HTML, is just to use a table to line everything up.

<form>
  <table>
    <tr>
      <td align="right">First Name:</td>
      <td align="left"><input type="text" name="first" /></td>
    </tr>
    <tr>
      <td align="right">Last Name:</td>
      <td align="left"><input type="text" name="last" /></td>
    </tr>
    <tr>
      <td align="right">Email:</td>
      <td align="left"><input type="text" name="email" /></td>
    </tr>
  </table>
</form>


问:
Crop Rectangle returned by minAreaRect OpenCV [Python]
minAreaRect in OpenCV returns a rotated rectangle. How do I crop this part of the image which is inside the rectangle?

boxPoints returns the co-ordinates of the corner points of the rotated rectangle so one can access the pixels by looping through the points inside the box, but is there a faster way to crop in Python?

EDIT

See code in my answer below.

答:
here a function that does this task:

```<code>import cv2
import numpy as np

def crop_minAreaRect(img, rect):

    # rotate img
    angle = rect[2]
    rows,cols = img.shape[0], img.shape[1]
    M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1)
    img_rot = cv2.warpAffine(img,M,(cols,rows))

    # rotate bounding box
    rect0 = (rect[0], rect[1], 0.0)
    box = cv2.boxPoints(rect0)
    pts = np.int0(cv2.transform(np.array([box]), M))[0]
    pts[pts < 0] = 0

    # crop
    img_crop = img_rot[pts[1][1]:pts[0][1],
                       pts[1][0]:pts[2][0]]

    return img_crop
</code>```

here an example usage

```<code># generate image
img = np.zeros((1000, 1000), dtype=np.uint8)
img = cv2.line(img,(400,400),(511,511),1,120)
img = cv2.line(img,(300,300),(700,500),1,120)

# find contours / rectangle
_,contours,_ = cv2.findContours(img, 1, 1)
rect = cv2.minAreaRect(contours[0])

# crop
img_croped = crop_minAreaRect(img, rect)

# show
import matplotlib.pylab as plt
plt.figure()
plt.subplot(1,2,1)
plt.imshow(img)
plt.subplot(1,2,2)
plt.imshow(img_croped)
plt.show()
</code>```

this is the output

Body:
here a function that does this task:

import cv2
import numpy as np

def crop_minAreaRect(img, rect):

    # rotate img
    angle = rect[2]
    rows,cols = img.shape[0], img.shape[1]
    M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1)
    img_rot = cv2.warpAffine(img,M,(cols,rows))

    # rotate bounding box
    rect0 = (rect[0], rect[1], 0.0)
    box = cv2.boxPoints(rect0)
    pts = np.int0(cv2.transform(np.array([box]), M))[0]
    pts[pts < 0] = 0

    # crop
    img_crop = img_rot[pts[1][1]:pts[0][1],
                       pts[1][0]:pts[2][0]]

    return img_crop

here an example usage

# generate image
img = np.zeros((1000, 1000), dtype=np.uint8)
img = cv2.line(img,(400,400),(511,511),1,120)
img = cv2.line(img,(300,300),(700,500),1,120)

# find contours / rectangle
_,contours,_ = cv2.findContours(img, 1, 1)
rect = cv2.minAreaRect(contours[0])

# crop
img_croped = crop_minAreaRect(img, rect)

# show
import matplotlib.pylab as plt
plt.figure()
plt.subplot(1,2,1)
plt.imshow(img)
plt.subplot(1,2,2)
plt.imshow(img_croped)
plt.show()

this is the output


问:
Is there a downside to this type of caching in PHP?
Say, for example, I've got a blog post with some user comments.

What I want to do is serve a static page. If the user posts a comment, it will generate a new file (with the new content added) and serve that instead.

It's a very, very simple model. Almost too simple, so I'm wondering if there are downsides to it.

答:
It's a very, very simple model. Almost
  too simple, so I'm wondering if there
  are downsides to it.

It is almost perfect(maybe for simple websites/small blog perfect). But couple of downside to this approach:

the data is not stored inside memory, which is way faster then your disc.

Your site is static again with this approach.


问:
Cannot receive push notification on iOS from Firebase 3.2.0 topics
I followed the tutorial by google on https://firebase.google.com/docs/notifications/ios/console-topics#receive_and_handle_topic_messages to subscribe to a Firebase topic on my iOS app.

```<code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {

    FIRMessaging.messaging().subscribeToTopic("/topics/Notifications")

    let homeViewController = UINavigationController(rootViewController: HomeViewController())

    UINavigationBar.appearance().translucent = false
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = homeViewController

    window?.makeKeyAndVisible()
    return true
}
</code>```

However, when I send a topic push notification out from the Firebase console. I could not receive any push notifications. But when I send out push notification to user segment from the console, the push is working perfectly. When I check the Xcode console, I am seeing this FIRMessaging error.

```<code>2016-05-31 11:11:47.893: <FIRMessaging/WARNING> Cannot subscribe to topic: /topics/Notifications with token: (null)
</code>```

I've tried to search for this error but have no luck finding anything. I am not sure if this is the problem that is causing my app to not receive any push from topics.

Does anyone have this issue and know how to solve it?

答:
The accepted solution did not work for me. The token is not always available when application:didRegisterUserNotificationSettings: is called.
For example if application is freshly installed and starts for the first time FIRInstanceID.instanceID().token() returns nil.

You need to make sure application calls subscribeToTopic: after the token is available.
I ended up with creating a helper object that enqueues subscribeToTopic:, unsubscribeFrom: calls and executes them in FIFO order after the token arrives.

```<code>class FIRMessagingHelper {

    private let queue: OperationQueue

    init() {
        queue = OperationQueue()
        queue.maxConcurrentOperationCount = 1
        queue.addOperation(TokenReadyOperation())
    }

    func subscribeTo(topic: String) {
        queue.addOperation {
            OperationQueue.main.addOperation({
                FIRMessaging.messaging().subscribeToTopic(topic)
            })
        }
    }

    func unsubscribeFrom(topic: String) {
        queue.addOperation {
            OperationQueue.main.addOperation({
                FIRMessaging.messaging().unsubscribeFromTopic(topic)
            })
        }
    }
}
</code>```

TokenReadyOperation waits until the token appears. AsynchronousOperation is used as the base class to minimize boilerplate.

```<code>class TokenReadyOperation : AsynchronousOperation {

    override init() {
        super.init()
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(TokenReadyOperation.tokenRefreshed(notification:)),
                                               name: .firInstanceIDTokenRefresh,
                                               object: nil)
    }

    override func didStart() {
        finishIfTokenAvailable()
    }

    private func finishIfTokenAvailable() {
        guard FIRInstanceID.instanceID().token() != nil else { return }
        markFinished()
    }

    /// Posted every time token changes
    @objc private func tokenRefreshed(notification: Notification) {
        finishIfTokenAvailable()
    }
}
</code>```

Few things to keep in mind:

App must call FIRApp.configure() or FIRApp.configureWithOptions(_:) prior making any Firebase calls (as Todd Kerpelman mentioned)

subscribeToTopic:, unsubscribeFrom: are not thread safe and must be executed on main thread

Topic names has to be in "/topics/*" format (as henmer mentioned)

Make sure to use different configuration plist for debug and App Store release of your app. See FIRApp.configureWithOptions(_:) documentation.

Date & Time should be current, otherwise the token may not be delivered.

Make sure to use the newest framework version. I had issues with notification delivery with the SDK released around January 2017.

Body:
I followed the tutorial by google on https://firebase.google.com/docs/notifications/ios/console-topics#receive_and_handle_topic_messages to subscribe to a Firebase topic on my iOS app.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {

    FIRMessaging.messaging().subscribeToTopic("/topics/Notifications")

    let homeViewController = UINavigationController(rootViewController: HomeViewController())

    UINavigationBar.appearance().translucent = false
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = homeViewController

    window?.makeKeyAndVisible()
    return true
}

However, when I send a topic push notification out from the Firebase console. I could not receive any push notifications. But when I send out push notification to user segment from the console, the push is working perfectly. When I check the Xcode console, I am seeing this FIRMessaging error.

2016-05-31 11:11:47.893: <FIRMessaging/WARNING> Cannot subscribe to topic: /topics/Notifications with token: (null)

I've tried to search for this error but have no luck finding anything. I am not sure if this is the problem that is causing my app to not receive any push from topics.

Does anyone have this issue and know how to solve it?

Body:
The accepted solution did not work for me. The token is not always available when application:didRegisterUserNotificationSettings: is called.
For example if application is freshly installed and starts for the first time FIRInstanceID.instanceID().token() returns nil.

You need to make sure application calls subscribeToTopic: after the token is available.
I ended up with creating a helper object that enqueues subscribeToTopic:, unsubscribeFrom: calls and executes them in FIFO order after the token arrives.

class FIRMessagingHelper {

    private let queue: OperationQueue

    init() {
        queue = OperationQueue()
        queue.maxConcurrentOperationCount = 1
        queue.addOperation(TokenReadyOperation())
    }

    func subscribeTo(topic: String) {
        queue.addOperation {
            OperationQueue.main.addOperation({
                FIRMessaging.messaging().subscribeToTopic(topic)
            })
        }
    }

    func unsubscribeFrom(topic: String) {
        queue.addOperation {
            OperationQueue.main.addOperation({
                FIRMessaging.messaging().unsubscribeFromTopic(topic)
            })
        }
    }
}

TokenReadyOperation waits until the token appears. AsynchronousOperation is used as the base class to minimize boilerplate.

class TokenReadyOperation : AsynchronousOperation {

    override init() {
        super.init()
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(TokenReadyOperation.tokenRefreshed(notification:)),
                                               name: .firInstanceIDTokenRefresh,
                                               object: nil)
    }

    override func didStart() {
        finishIfTokenAvailable()
    }

    private func finishIfTokenAvailable() {
        guard FIRInstanceID.instanceID().token() != nil else { return }
        markFinished()
    }

    /// Posted every time token changes
    @objc private func tokenRefreshed(notification: Notification) {
        finishIfTokenAvailable()
    }
}

Few things to keep in mind:

App must call FIRApp.configure() or FIRApp.configureWithOptions(_:) prior making any Firebase calls (as Todd Kerpelman mentioned)

subscribeToTopic:, unsubscribeFrom: are not thread safe and must be executed on main thread

Topic names has to be in "/topics/*" format (as henmer mentioned)

Make sure to use different configuration plist for debug and App Store release of your app. See FIRApp.configureWithOptions(_:) documentation.

Date & Time should be current, otherwise the token may not be delivered.

Make sure to use the newest framework version. I had issues with notification delivery with the SDK released around January 2017.


问:
Gluu Server continuously giving me 503 error - Service Unavailable
I have EC2 instance (Redhat 7.* 64 bit) and I have installed gluu-server-3.0.1 on that ec2 instance.
I followed this tutorial to install the gluu-server on the ec2 instnce

Gluu-server installation (official)

I installed carefully following each and every step listed there on above link. Every step and command of the installation process was success (No problem with installation).

Finally when I visit the gluu-server link it redirects me to the correct link automatically. I visit http://example.com redirect me to https://example.com/identity but the gives me error 503.

Error

The server is temporarily unable to service your request due to
  maintenance downtime or capacity problems. Please try again later.

答: If you want to post this question on the Gluu Support forum, you're more likely to get a response from the team.</p>


问:
How to dynamically define dependencies for a marko template being rendered in express JS route using lasso?
For example: Consider a route /theme
The route should render itself in the theme (read: LESS color variables) specified as a route/query param.
Based on the theme parameter, a custom JS script may also need to be injected.

The scripts and styles may or may not be included depending on the provided parameter (which rules out preconfiguring a lasso or using a bower.json). This also means that the dependencies must be specified right before the route renders the template.

I am currently using Marko v4 + ExpressJS + Lasso + Less + lasso-marko + lasso-less

I am not posting code as it's a little all over the place after trying so many things out. Please let me know if the description is not clear enough. Will try putting together a sandbox for demonstration purposes.

UPDATE: Adding in Core files and Directory Structure

```<code>sandbox
|- components
|  |- app-main.marko
|- dependencies
|  |- theme1
|     |- main.js
|     |- variables.less
|  |- theme2
|     |- main.js
|     |- variables.less
|- node_modules
|- public
|- templates
|  |- base
|     |- index.marko
|     |- style.less
|     |- browser.json
|- index.js
|- package.json

//index.js
var markoExpress = require('marko/express');
require('marko/node-require');

var express = require('express');

var app = express();

var compression = require('compression');
var isProduction = process.env.NODE_ENV === 'production';

var lasso = require('lasso');
lasso.configure({
    plugins: [
        'lasso-marko',
        'lasso-less'
    ],
    outputDir: __dirname + '/public',
    bundlingEnabled: isProduction,
    minify: isProduction,
    fingerprintsEnabled: isProduction,
});

app.use(express.static('public'));
app.use(markoExpress());

app.use(compression());

app.use(require('lasso/middleware').serveStatic());

var template = require('./templates/base');
app.get('/:pub', function (req, res) {
    var pub = req.params.pub || "theme1";

    res.marko(template, {
        theme:pub
    });
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
    if (process.send) {
        process.send('online');
    }
});

//browser.json
{
    "dependencies": [
        {
            "if-flag": "theme1",
            "dependencies": [
                "less-import: ../../dependencies/theme1/variables.less",
                "../../dependencies/theme1/main.js"
            ]
        },
        {
            "if-flag": "theme2",
            "dependencies": [
                "less-import: ../../dependencies/theme2/variables.less",
                "../../dependencies/theme2/main.js"
            ]
        }
    ]
}

<!-- index.marko -->
<lasso-page package-path="./browser.json" flags="['${input.theme}']"/>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
  <title>Test Template</title>

  <!-- CSS includes -->
  <lasso-head/>

</head>
<body>

 <!-- Top-level UI component: -->
<include('../../components/app-main',input) />

<lasso-body/>
</body>
</html>

//style.less
main {
    background-color: @bgcolor;
    color: @fgcolor;
    width: 100%;
    height: 100%;
}

// ~/dependencies/theme1/variables.less
@bgcolor: red;
@fgcolor: white;

// ~/dependencies/theme1/main.js
alert("theme1");

<!-- app-main.marko -->
<main>TADAAA</main>
</code>```

答:
Lasso supports conditional dependencies based on "flags": https://github.com/lasso-js/lasso#conditional-dependencies

If you make the theme one of the flags you could then use the flag to conditionally pull in Less variables or other dependencies in your browser.json:

```<code>{
    "dependencies": [
        {
            "if-flag": "theme1",
            "dependencies": [
                "less-import: ./theme1/variables.less"
            ]
        },
        {
            "if-flag": "theme2",
            "dependencies": [
                "less-import: ./theme2/variables.less"
            ]
        }
    ]
}
</code>```

You could do a prebuild of all of the themes or you could use Lasso at runtime to dynamically build the page JS/CSS.

Hope that solves your problem.

Body:
For example: Consider a route /theme
The route should render itself in the theme (read: LESS color variables) specified as a route/query param.
Based on the theme parameter, a custom JS script may also need to be injected.

The scripts and styles may or may not be included depending on the provided parameter (which rules out preconfiguring a lasso or using a bower.json). This also means that the dependencies must be specified right before the route renders the template.

I am currently using Marko v4 + ExpressJS + Lasso + Less + lasso-marko + lasso-less

I am not posting code as it's a little all over the place after trying so many things out. Please let me know if the description is not clear enough. Will try putting together a sandbox for demonstration purposes.

UPDATE: Adding in Core files and Directory Structure

sandbox
|- components
|  |- app-main.marko
|- dependencies
|  |- theme1
|     |- main.js
|     |- variables.less
|  |- theme2
|     |- main.js
|     |- variables.less
|- node_modules
|- public
|- templates
|  |- base
|     |- index.marko
|     |- style.less
|     |- browser.json
|- index.js
|- package.json

//index.js
var markoExpress = require('marko/express');
require('marko/node-require');

var express = require('express');

var app = express();

var compression = require('compression');
var isProduction = process.env.NODE_ENV === 'production';

var lasso = require('lasso');
lasso.configure({
    plugins: [
        'lasso-marko',
        'lasso-less'
    ],
    outputDir: __dirname + '/public',
    bundlingEnabled: isProduction,
    minify: isProduction,
    fingerprintsEnabled: isProduction,
});

app.use(express.static('public'));
app.use(markoExpress());

app.use(compression());

app.use(require('lasso/middleware').serveStatic());

var template = require('./templates/base');
app.get('/:pub', function (req, res) {
    var pub = req.params.pub || "theme1";

    res.marko(template, {
        theme:pub
    });
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
    if (process.send) {
        process.send('online');
    }
});

//browser.json
{
    "dependencies": [
        {
            "if-flag": "theme1",
            "dependencies": [
                "less-import: ../../dependencies/theme1/variables.less",
                "../../dependencies/theme1/main.js"
            ]
        },
        {
            "if-flag": "theme2",
            "dependencies": [
                "less-import: ../../dependencies/theme2/variables.less",
                "../../dependencies/theme2/main.js"
            ]
        }
    ]
}

<lasso-page package-path="./browser.json" flags="['${input.theme}']"/>
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
  <title>Test Template</title>

  <lasso-head/>

<include('../../components/app-main',input) />

<lasso-body/>

//style.less
main {
    background-color: @bgcolor;
    color: @fgcolor;
    width: 100%;
    height: 100%;
}

// ~/dependencies/theme1/variables.less
@bgcolor: red;
@fgcolor: white;

// ~/dependencies/theme1/main.js
alert("theme1");

TADAAA

Body:
Lasso supports conditional dependencies based on "flags": https://github.com/lasso-js/lasso#conditional-dependencies

If you make the theme one of the flags you could then use the flag to conditionally pull in Less variables or other dependencies in your browser.json:

{
    "dependencies": [
        {
            "if-flag": "theme1",
            "dependencies": [
                "less-import: ./theme1/variables.less"
            ]
        },
        {
            "if-flag": "theme2",
            "dependencies": [
                "less-import: ./theme2/variables.less"
            ]
        }
    ]
}

You could do a prebuild of all of the themes or you could use Lasso at runtime to dynamically build the page JS/CSS.

Hope that solves your problem.


问:
Angular2 doesn't work with Apache
I just start learn Angular2, and I want run writed application on Apache server, but my index file don't work like that from tutorial : https://angular.io/guide/quickstart</p>

答:
ng2 apps are SPAs (Single page apps).

Thus we must deliver index.html (our single page) on each request.

If we are not doing this then our app will load OK initially but when we change route and click refresh we get a 404 or some other error.

Typicaly rules for a server for an ng2 SPA will look something like ..

```<code>^/api/(.*)$ http://localhost:51108/api/$1 [P]
^[^\\.]*$ /index.html [L]
</code>```

The first line here rewrites all requests starting with /api to our API server.

The second line causes all other requests to serve index.html - this is how we achieve our SPA

The exact syntax of these rules may vary but this info should point you in the right direction to help you resolve this issue.

Title: Angular2 doesn't work with Apache

Body:
ng2 apps are SPAs (Single page apps).

Thus we must deliver index.html (our single page) on each request.

If we are not doing this then our app will load OK initially but when we change route and click refresh we get a 404 or some other error.

Typicaly rules for a server for an ng2 SPA will look something like ..

^/api/(.*)$ http://localhost:51108/api/$1 [P]
^[^\\.]*$ /index.html [L]

The first line here rewrites all requests starting with /api to our API server.

The second line causes all other requests to serve index.html - this is how we achieve our SPA

The exact syntax of these rules may vary but this info should point you in the right direction to help you resolve this issue.


问:
Java accessing ServletContext from within restlet Resource
I am using Tomcat server in java and wanted to be able to access the ServletContext from the restlet Resource in order to access my cached DataSource object (to pool mysql connections). org.restlet.resource.Resource comes with a Context object but that is not in any way related to the ServletContext. So after some googling around, I found the following:

```<code>final String contextKey = "org.restlet.ext.servlet.ServletContext";
final String poolKey = "MyCachedDBPool";
final Map<String, Object> attrs = getContext().getAttributes();
final ServletContext ctx = (ServletContext) attrs.get(contextKey);
if (ctx == null) {
  throw new Exception("Cannot find ServletContext: " + contextKey);
}
final DataSource ds = (DataSource) ctx.getAttribute(poolKey);
if (ds == null) {
  throw new DetourQAException("DataSource not stored in context"
    + poolKey + "attr");
}
</code>```

But it returns null for the ServletContext. Has anybody successfully accessed the ServletContext from within the restlet resource and how did you do it?

If this is not the recommended way to do connection pooling, what is the best way to do connection pooling in the restlet?

答:
This was the way to do it before Restlet 2.0 (actually I think they changed it around 2.0-M5, or so). Anyway, the way you'd do it now is:

```<code>ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes().get( "org.restlet.ext.servlet.ServletContext" );
</code>```

Hope that helps.

Body:
I am using Tomcat server in java and wanted to be able to access the ServletContext from the restlet Resource in order to access my cached DataSource object (to pool mysql connections). org.restlet.resource.Resource comes with a Context object but that is not in any way related to the ServletContext. So after some googling around, I found the following:

final String contextKey = "org.restlet.ext.servlet.ServletContext";
final String poolKey = "MyCachedDBPool";
final Map<String, Object> attrs = getContext().getAttributes();
final ServletContext ctx = (ServletContext) attrs.get(contextKey);
if (ctx == null) {
  throw new Exception("Cannot find ServletContext: " + contextKey);
}
final DataSource ds = (DataSource) ctx.getAttribute(poolKey);
if (ds == null) {
  throw new DetourQAException("DataSource not stored in context"
    + poolKey + "attr");
}

But it returns null for the ServletContext. Has anybody successfully accessed the ServletContext from within the restlet resource and how did you do it?

If this is not the recommended way to do connection pooling, what is the best way to do connection pooling in the restlet?

Body:
This was the way to do it before Restlet 2.0 (actually I think they changed it around 2.0-M5, or so). Anyway, the way you'd do it now is:

ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes().get( "org.restlet.ext.servlet.ServletContext" );

Hope that helps.


问:
Cut String at Special Position VBA
I got this string here: \server\Documents\test\\954076
how i check if there is a \ a second time and how i cut it then off?
So that \server\Documents\test\\954076 is gonna be \server\Documents\test\954076</p>

答:
if you're worried about double repetitions then it suffices

```<code>Dim strng As String

strng = "\server\Documents\test\\\954076"

strng = Replace(strng, "\\", "\")
</code>```

if you want to handle multiple repetitions then:

```<code>Dim strng As String

strng = "\server\Documents\test\\\954076"

Do While Len(strng) - Len(Replace(strng, "\\", "\")) > 0
    strng = Replace(strng, "\\", "\")
Loop
</code>```

Title: Cut String at Special Position VBA

Body:
if you're worried about double repetitions then it suffices

Dim strng As String

strng = "\server\Documents\test\\\954076"

strng = Replace(strng, "\\", "\")

if you want to handle multiple repetitions then:

Dim strng As String

strng = "\server\Documents\test\\\954076"

Do While Len(strng) - Len(Replace(strng, "\\", "\")) > 0
    strng = Replace(strng, "\\", "\")
Loop


问:
Convert all the elements of an array to individual strings
I need to convert all elements of $values_x to individual strings. For eg:If it has (2010,2011,2012), i need it to be ('2010',2011','2012')</p>
```<code>$values_x = array();
for ($i = 0; $i < count( $series[0]['data'] ); $i++ ) {
    $values_x[] = $series[0]['data'][$i][0];
}

$values_y = array();
for ($i = 0; $i < count( $series[0]['data'] ); $i++ ) {
    $values_y[] = $series[0]['data'][$i][1];
}

$categories = array(
    "label"  => $label_x,
    "values" => $values_x,
    "colors" => $eco_chart_colors,
);

$series = array("label" => null, "values" => array( array("data" => $values_y)));
</code>```

答:
Why dont you simply do following, You can see your output using following two lines of code.

```<code>$string_vals = array();
$string_vals[] = "'".$categories['values']."'";
</code>```

Simply Concatenate Single Quotation marks.
So, Something like this

```<code>$string_vals = array();
foreach($categories as $cat){
    $string_vals[] = "'".$cat['values']."'";
}
print_r($string_vals);
</code>```

Body:
I need to convert all elements of $values_x to individual strings. For eg:If it has (2010,2011,2012), i need it to be ('2010',2011','2012')

$values_x = array();
for ($i = 0; $i < count( $series[0]['data'] ); $i++ ) {
    $values_x[] = $series[0]['data'][$i][0];
}

$values_y = array();
for ($i = 0; $i < count( $series[0]['data'] ); $i++ ) {
    $values_y[] = $series[0]['data'][$i][1];
}

$categories = array(
    "label"  => $label_x,
    "values" => $values_x,
    "colors" => $eco_chart_colors,
);

$series = array("label" => null, "values" => array( array("data" => $values_y)));

Body:
Why dont you simply do following, You can see your output using following two lines of code.

$string_vals = array();
$string_vals[] = "'".$categories['values']."'";

Simply Concatenate Single Quotation marks.
So, Something like this

$string_vals = array();
foreach($categories as $cat){
    $string_vals[] = "'".$cat['values']."'";
}
print_r($string_vals);


问:
HTTP Status 500 – Internal Server Error
I am trying to update my DB rows by using primary key.But facing this Exception

Exception

```<code>HTTP Status 500 – Internal Server Error

Type Exception Report

Message Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</code>```

Controller

```<code>@RequestMapping(value="edit/product/success" ,method=RequestMethod.POST)
public ModelAndView editProduct(@ModelAttribute ("prdt") Product p)
{
ModelAndView model=new ModelAndView("pl");
model.addObject("Update","Updated Successfully");
pd.update(p);
return model;
}
</code>```

Dao Impl

```<code>public void update( Product p) {
Session session=sessionFactory.openSession();
session.update(p);
session.flush();
session.close();
}
</code>```

Jsp

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ include file="header.jsp"%>
<%@ page isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page isELIgnored="false" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#mfg" ).datepicker();
  } );
  </script>
</head>
<body>
<br>

<h2 align="center">PRODUCT FORM</h2><hr>
<div class="col-md-2 "></div>
<div align="center"><div class="container"><div class="col-md-8 ">

<form:form method="POST" action="${pageContext.request.contextPath}/edit/product/success" commandName="prdt" enctype="multipart/form-data" >
<table class="table table-hover">

<tr>
<td> <form:label  path="product_Name"> Enter Product Name</form:label></td>
<td><form:input type="text" path="product_Name" class="form-control" value="${d.product_Name }"/></td>
</tr>
<tr>
<td> <form:label path="descripction"> Enter Product Descripction</form:label></td>
<td><form:input type="text" path="descripction"  class="form-control" value="${d.descripction }"/></td>
</tr>
<tr>
 <td> <form:label  path="price"> Enter Product Price</form:label></td>
<td><form:input type="text" path="price"  class="form-control" value="${d.price }" />
</td></tr>
<tr>
<td> <form:label  path="mfg_Date"> Enter Manufacture Date</form:label></td>
<td><form:input type="text" id="mfg" path="mfg_Date" class="form-control" value ="${d.mfg_Date}"/></td>

</tr>
<tr>
<td> <label> Choose Image</label></td>
<td><form:input type="file" path="image" class="form-control" /></td>
</tr>

</table>
 <input type="submit" class="btn btn-primary btn-block" value="Save Changes" class="form-control"/>

</form:form>

</div></div></div></body>
</html>
</code>```

please check and let me know my Mistake..i have looked in it.but not found any irregularity.

Note:

Data retrieve works fine.facing trouble in Update only

答:
Check the product entity which u are trying to save to the database. Hibernate tries to look up for an entity with the ID(Primary key value), and if the pk value is changed in the entity and the update is called on this entity then the above error occurs.

Check the entity is having the same id, or the id getting replaced or setting to null somewhere. The id may be null in your case.

Title: HTTP Status 500 – Internal Server Error

Body:
I am trying to update my DB rows by using primary key.But facing this Exception

Exception

HTTP Status 500 – Internal Server Error

Type Exception Report

Message Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Controller

@RequestMapping(value="edit/product/success" ,method=RequestMethod.POST)
public ModelAndView editProduct(@ModelAttribute ("prdt") Product p)
{
ModelAndView model=new ModelAndView("pl");
model.addObject("Update","Updated Successfully");
pd.update(p);
return model;
}

Dao Impl

public void update( Product p) {
Session session=sessionFactory.openSession();
session.update(p);
session.flush();
session.close();
}

Jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ include file="header.jsp"%>
<%@ page isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page isELIgnored="false" %>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

PRODUCT FORM

<form:form method="POST" action="${pageContext.request.contextPath}/edit/product/success" commandName="prdt" enctype="multipart/form-data" >

 <form:label  path="product_Name"> Enter Product Name</form:label>
<form:input type="text" path="product_Name" class="form-control" value="${d.product_Name }"/>

 <form:label path="descripction"> Enter Product Descripction</form:label>
<form:input type="text" path="descripction"  class="form-control" value="${d.descripction }"/>

  <form:label  path="price"> Enter Product Price</form:label>
<form:input type="text" path="price"  class="form-control" value="${d.price }" />

 <form:label  path="mfg_Date"> Enter Manufacture Date</form:label>
<form:input type="text" id="mfg" path="mfg_Date" class="form-control" value ="${d.mfg_Date}"/>

  Choose Image
<form:input type="file" path="image" class="form-control" />

 <input type="submit" class="btn btn-primary btn-block" value="Save Changes" class="form-control"/>

</form:form>

please check and let me know my Mistake..i have looked in it.but not found any irregularity.

Note:

Data retrieve works fine.facing trouble in Update only


问:
Get path to a file in a bundle with C++ (CFBundleGetMainBundle)
I'm writing an iOS app which has a C++ component. In order to get the main bundle many other answers recommend using this:

```<code>CFBundleRef mainBundle = CFBundleGetMainBundle();
</code>```

This is fine, but it seems I have to include something like

```<code>#include <UIKit/UIKit.h>
</code>```

at the top of my file.  But doing this throws a bunch of errors like:

```<code>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h:494:9: Unknown type name 'NSString'
</code>```

I assume this has something to do with my C++ code. I'm wondering if there's something else I can include which doesn't throw this error? If not, what is the right way of accessing the path to a file in the C++ code?

答:
This is due to C's concept of "compilation units". Basically, all headers you include in a source file have to be written in the language of that file. Since both Objective C and C++ are (roughly) supersets of C, you can include C headers (like CoreFoundation) in both C++ and Objective-C source files.

However, a C++ compiler does not know how to read an Objective-C file, and an Objective-C compiler does not know how to read a C++ file, so if you include an Objective-C header like UIKit from a C++ file, the C++ compiler will give you lots of error messages.

To avoid this issue, you should look up the documentation for CFBundle. Turns out, CFBundle is part of CoreFoundation, which is a C API and thus can easily be called from a C++ file, you just have to include the correct header.

While including UIKit might work as well, that is simply a side effect of the fact that some parts of UIKit are based on CoreFoundation, and use it as well, and therefor include CoreFoundation.

However, not all APIs are available as a C version. If you want to call something from UIKit or AVFoundation or so, you may have to create a C "wrapper function" that does what you want to do, and internally is implemented in Objective C. As long as you make sure that only the .m implementation file contains Objective-C, and the header file just exposes the function and standard C data types like int or bool, you can then call the function from a C++ application just like you would any other plain C function (which will likely require use of extern "C" like it would with regular C).

There is also something called "Objective-C++" (file suffix .mm), which is a "pseudo-language" that lets you mix Objective-C and C++ in an implementation file, but even with that you would have to be careful not to expose any of the Objective-C in your header to be able to call it from a plain C++ file.

Body:
I'm writing an iOS app which has a C++ component. In order to get the main bundle many other answers recommend using this:

CFBundleRef mainBundle = CFBundleGetMainBundle();

This is fine, but it seems I have to include something like

#include <UIKit/UIKit.h>

at the top of my file.  But doing this throws a bunch of errors like:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h:494:9: Unknown type name 'NSString'

I assume this has something to do with my C++ code. I'm wondering if there's something else I can include which doesn't throw this error? If not, what is the right way of accessing the path to a file in the C++ code?


问:
Undefined symbols for architecture x86_64 when using Tesseract
I am using tesseract provided by google. After following this tutorial, i finally built finish my app. However, when i run it, i run into the problem of undefined symbols. This is the error

```<code>Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_G8Tesseract", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

How do i fix this issue? I tried searching online but none of the solutions worked for me. I tried reinstalling the pods and updating it. Then i faced this error

```<code>clang: error: no such file or directory: '/Users/admin/Desktop/tst/Pods/Target Support Files/Pods-tst/Pods-tst-dummy.m'
clang: error: no input files
</code>```

When i tried redoing the project i get his error

```<code>Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_G8Tesseract", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

答:
Since Tesseract requires libstdc++.6.0.9.dylib (or libstdc++.6.0.9.tbd if libstdc++.6.0.9.dylib is unavailable in your current Xcode version) and CoreImage.framework you’ll need to link both of these libraries in.

In the General tab, scroll down to Linked Frameworks and Libraries.

There should be only one file here: TesseractOCR.framework, which you just added. Click the + button underneath the list. Find both libstdc++.dylib (or libstdc++.6.0.9.tbd) and CoreImage.framework and add them to your project.

Body:
I am using tesseract provided by google. After following this tutorial, i finally built finish my app. However, when i run it, i run into the problem of undefined symbols. This is the error

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_G8Tesseract", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

How do i fix this issue? I tried searching online but none of the solutions worked for me. I tried reinstalling the pods and updating it. Then i faced this error

clang: error: no such file or directory: '/Users/admin/Desktop/tst/Pods/Target Support Files/Pods-tst/Pods-tst-dummy.m'
clang: error: no input files

When i tried redoing the project i get his error

Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_G8Tesseract", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


问:
Concat the results of find
I'm trying to concatenate the results of find in Bash. So I got the following code:

```<code>c="sh -content_image in.jpg, style_image "

find t/Pictures -name "*.jpg"| while read line; do
    c=${c}",",
    c=${c}"$line"
    echo $line

 done

echo $c
</code>```

This first prints all the files in t/Pictures and then the string sh -content_image in.jpg, style_image. While what it's supposed to do is first print all the files and then print that string followed by all of the

So the current output looks like this:

```<code>t/Pictures/nature/ActiOn_89.jpg
t/Pictures/nature/ActiOn_27.jpg
t/Pictures/nature/ActiOn_47.jpg
t/Pictures/nature/ActiOn_54.jpg
sh -content_image in.jpg, style_image
</code>```

but I want it too look like

```<code>t/Pictures/nature/ActiOn_89.jpg
t/Pictures/nature/ActiOn_27.jpg
t/Pictures/nature/ActiOn_47.jpg
t/Pictures/nature/ActiOn_54.jpg
sh -content_image in.jpg, style_image t/Pictures/nature/ActiOn_89.jpg,t/Pictures/nature/ActiOn_27.jpg,t/Pictures/nature/ActiOn_47.jpg,t/Pictures/nature/ActiOn_54.jpg
</code>```

Any idea what I'm doing wrong?

答:
You can do:</p>

```<code>c="sh -content_image in.jpg, style_image "

while IFS= read -rd '' line; do
    echo "$line"
    c+="$line,"
done < <(find t/Pictures -name "*.jpg" -print0)

# strip trailing comma
c="${c%,}"
</code>```

Title: Concat the results of find

Body:
I'm trying to concatenate the results of find in Bash. So I got the following code:

c="sh -content_image in.jpg, style_image "

find t/Pictures -name "*.jpg"| while read line; do
    c=${c}",",
    c=${c}"$line"
    echo $line

 done

echo $c

This first prints all the files in t/Pictures and then the string sh -content_image in.jpg, style_image. While what it's supposed to do is first print all the files and then print that string followed by all of the

So the current output looks like this:

t/Pictures/nature/ActiOn_89.jpg
t/Pictures/nature/ActiOn_27.jpg
t/Pictures/nature/ActiOn_47.jpg
t/Pictures/nature/ActiOn_54.jpg
sh -content_image in.jpg, style_image

but I want it too look like

t/Pictures/nature/ActiOn_89.jpg
t/Pictures/nature/ActiOn_27.jpg
t/Pictures/nature/ActiOn_47.jpg
t/Pictures/nature/ActiOn_54.jpg
sh -content_image in.jpg, style_image t/Pictures/nature/ActiOn_89.jpg,t/Pictures/nature/ActiOn_27.jpg,t/Pictures/nature/ActiOn_47.jpg,t/Pictures/nature/ActiOn_54.jpg

Any idea what I'm doing wrong?

Body:
You can do:

c="sh -content_image in.jpg, style_image "

while IFS= read -rd '' line; do
    echo "$line"
    c+="$line,"
done < <(find t/Pictures -name "*.jpg" -print0)

# strip trailing comma
c="${c%,}"


问:
Can not run other website in my office
We can not run any other site on office pc on any pc or laptop connected to my office modem
 why can I only run my company website on office

we tried to change office modem so We can run all sites but my compony website did not open

we tried to connect these two modem together but this did 't work
The first modem is netgenie on which we can only run company website we do not have login password

The second modem is d-link on which other sites could run but we could not run compant website if we connect through it removing netgenie modem
the ip address for company website is 172.16.10.120 port 8079

答:
Your company website is an intranet site, it does not require general internet access.

Your d-link modem likely has a built-in DHCP server which is turned on by default, and probably provides addresses in the range of 192.168... so your office PC will no longer be on the same subnet as the company website, and therefore cannot access it, although the rest of the internet is available to you.

Title: Can not run other website in my office