问:
How to apply search also in child node

demo.py

```<code>import sqlite3 as lite

from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.treeview import TreeView, TreeViewLabel, TreeViewNode
from kivy.uix.label import Label
from kivy.properties import ObjectProperty,StringProperty

Window.size = (700, 530)

def populate_tree_view(tree_view, parent, node):
    if parent is None:
        tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
                                                     is_open=True))
    else:
        tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
                                                     is_open=True), parent)

    for child_node in node['children']:
        populate_tree_view(tree_view, tree_node, child_node)

tree = []

tree = [{'node_id': 'Capital Account',
         'children': [{'node_id': 'Reserves & Surplus',
                       'children': [{'node_id': '1.1.1',
                                     'children': [{'node_id': '1.1.1.1',
                                                   'children': []}]},
                                    {'node_id': '1.1.2',
                                     'children': []},
                                    {'node_id': '1.1.3',
                                     'children': []}]},
                       {'node_id': '1.2',
                        'children': []}]},
        {'node_id': 'Current Assests',
         'children': []}]

class TreeViewLabel(Label, TreeViewNode):
    pass

class TestViewLabel():
    pass

class TreeviewGroup(Popup):
    treeview = ObjectProperty(None)
    tv = ObjectProperty(None)
    ti = ObjectProperty()
    abc = StringProperty('c')

    def __init__(self, **kwargs):
        super(TreeviewGroup, self).__init__(**kwargs)
        self.tv = TreeView(root_options=dict(text=""),
                       hide_root=False,
                       indent_level=4)
        for branch in tree:
            populate_tree_view(self.tv, None, branch)
        self.remove_widgets()
        self.treeview.add_widget(self.tv)

    def remove_widgets(self):
        for child in [child for child in self.treeview.children]:
            self.treeview.remove_widget(child)

    def filter(self, f):
        self.treeview.clear_widgets()
        self.tv = TreeView(root_options=dict(text=""),
                           hide_root=False,
                           indent_level=4)
        new_tree = []
        for n in tree:
            if f.lower() in n['node_id'].lower():
                new_tree.append(n)
        for branch in new_tree:
            populate_tree_view(self.tv, None, branch)

        self.treeview.add_widget(self.tv)

class CityScreen(Screen):
    groupName = ObjectProperty(None)
    popup = ObjectProperty(None)
    statecode = StringProperty('')

    def display_states(self, instance):
        if len(instance.text) > 0:
            if self.popup is None:
                self.popup = TreeviewGroup()
            self.popup.filter(instance.text)
            self.popup.open()

    def select_node(self, node):
        '''Select a node in the tree.
            '''

class MyApp(App):

    def build(self):
        self.root = Builder.load_file('demo.kv')
        return self.root

if __name__ == '__main__':
    MyApp().run()
</code>```

demo.kv

```<code>#:kivy 1.10.0

<TreeViewLabel>:
    on_touch_down:
        app.root.stateName.text = self.text
        app.root.select_node(self)
        app.root.popup.dismiss()

<TestViewLabel>:
    on_touch_down:
        app.root.stateName.text = self.text
        app.root.select_node(self)
        app.root.popup.dismiss()

<TreeviewGroup>:
    id: treeview
    treeview: treeview
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False

    BoxLayout
        orientation: "vertical"
        TextInput:
            id: ti
            size_hint_y: .1
            text: root.abc
            on_text: root.filter(self.text)
        BoxLayout:
            id: treeview
            #on_press: root.select_node(self.text)
        Button:
            size_hint: 1, 0.1
            text: "Close"
            on_release: root.dismiss()

<CustomLabel@Label>:
    text_size: self.size
    valign: "middle"
    padding_x: 5

<SingleLineTextInput@TextInput>:
    multiline: False

<GreenButton@Button>:
    background_color: 1, 1, 1, 1
    size_hint_y: None
    height: self.parent.height * 0.150

CityScreen:
    stateName: stateName

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        CustomLabel:
            text: 'Text'

        SingleLineTextInput:
            id: stateName
            on_text: root.display_states(self)

        #Spinner:
            #text: "State Code"
            #values: ["111", "112", "113", "114"]
            #values: app.r
            #background_color: color_button if self.state == 'normal' else color_button_pressed
            #background_down: 'atlas://data/images/defaulttheme/spinner'
            #color: color_font
            #option_cls: Factory.get("MySpinnerOption")
            #size_hint: None, None

        GreenButton:
            text: 'Ok'
            on_press: root.insert_data(stateName.text)

        GreenButton:
            text: 'Cancel'
            on_press: app.stop()

        Label:

        Label:
</code>```

When i type something in text TextBox then a pop up will be show.Then how to pass value from text TextBox to searchbox in pop up.

SearchBox working perfect for parent node.It's not working for child node.How will this work?

答:
When i type something in text TextBox then a pop up will be show.Then how to pass value from text TextBox to searchbox in pop up like attached image.

Since you have the text input property in your popup when you open it you can pass the text:

```<code>...
<TreeviewGroup>:
    id: treeview
    treeview: treeview
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False
    ti: ti
    BoxLayout
        orientation: "vertical"
        TextInput:
            id: ti
            size_hint_y: .1
            on_text: root.filter(self.text)
</code>```

then in the .py:

```<code>...

class CityScreen(Screen):
    groupName = ObjectProperty(None)
    popup = ObjectProperty(None)
    statecode = StringProperty('')

    def display_states(self, instance):
        if len(instance.text) > 0:
            if self.popup is None:
                self.popup = TreeviewGroup()
            self.popup.ti.text = instance.text
            self.popup.filter(instance.text)
            self.popup.open()
...
</code>```

2 SearchBox working perfect for parent node.It's not working for child node.How will this work?

That was not very easy to do, that question deserved a bounty

To make a filter when the treeView has children that are also parents I do many recursion

first, add those functions to your .py

```<code>...
def get_children(n):
    '''get all the children in the node whithout her children'''
    if len(n['children']) == 0:
        return []
    else:
        children = [e['node_id'] for e in n['children']]
        for child in n['children']:
            children.extend([c for c in get_children(child)])
        return children

def get_children2(n, t):
    '''get the node with n as id'''
    if t is []:
        return False
    else:
        for child in t:
            if child['node_id'] == n:
                return child
            else:
                r = get_children2(n, child['children'])
                if r:
                    return r

def roots(n):
    '''return the roots (if a node have child it is a root)'''
    if len(n['children']) == 0:
        return [None]
    else:
        l = [n['node_id']]
        for c in n['children']:
            l.extend(roots(c))
        return l

def get_roots(t):
    '''this one is just to remove the None from the result of the first one'''
    fl = []
    for n in t:
        l = roots(n)
        li = []
        for e in l:
            if e is not None:
                li.append(e)
        fl.extend(li)
        if len(n['children']) == 0:
            fl.append(n['node_id'])
    return fl

...
</code>```

Now you can change the filter method of the TreeView:

```<code>...
class TreeviewGroup(Popup):
    treeview = ObjectProperty(None)
    tv = ObjectProperty(None)
    ti = ObjectProperty()

    ...

    def filter(self, f):
        self.tv = TreeView(root_options=dict(text=""),
                           hide_root=False,
                           indent_level=4)
        for branch in tree:
            populate_tree_view(self.tv, None, branch)
        self.remove_widgets()
        self.treeview.add_widget(self.tv)
        l = []
        l_roots = get_roots(tree)
        dict_roots = []
        for node in self.tv.iterate_all_nodes():
            l.append(node)
        for i in range(len(l)):
            if l[i].text in l_roots:
                dict_roots.append({'ind': i, 'id': l[i].text})
        roots_childs = {}
        for e in l:
            try:
                nod = get_children2(e.text, tree)
                roots_childs[e.text] = get_children(nod)
            except TypeError:
                pass
        to_remove = []
        for e in roots_childs:
            for child in roots_childs[e]:
                if child not in l_roots:
                    if f.lower() not in child.lower():
                        if child not in to_remove:
                            to_remove.append(child)
            n = 0
            for child in roots_childs[e]:
                if child in to_remove:
                    n += 1
            if n == len(roots_childs[e]):
                if f.lower() not in e.lower():
                    to_remove.append(e)
        for n in l:
            if n.text in to_remove:
                self.tv.remove_node(n)
</code>```

Update I have forgotten to add ti in the TreeViewGroop in the kv it's fixed now

Title: How to apply search also in child node

Body:
demo.py

import sqlite3 as lite

from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.treeview import TreeView, TreeViewLabel, TreeViewNode
from kivy.uix.label import Label
from kivy.properties import ObjectProperty,StringProperty

Window.size = (700, 530)

def populate_tree_view(tree_view, parent, node):
    if parent is None:
        tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
                                                     is_open=True))
    else:
        tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
                                                     is_open=True), parent)

    for child_node in node['children']:
        populate_tree_view(tree_view, tree_node, child_node)

tree = []

tree = [{'node_id': 'Capital Account',
         'children': [{'node_id': 'Reserves & Surplus',
                       'children': [{'node_id': '1.1.1',
                                     'children': [{'node_id': '1.1.1.1',
                                                   'children': []}]},
                                    {'node_id': '1.1.2',
                                     'children': []},
                                    {'node_id': '1.1.3',
                                     'children': []}]},
                       {'node_id': '1.2',
                        'children': []}]},
        {'node_id': 'Current Assests',
         'children': []}]

class TreeViewLabel(Label, TreeViewNode):
    pass

class TestViewLabel():
    pass

class TreeviewGroup(Popup):
    treeview = ObjectProperty(None)
    tv = ObjectProperty(None)
    ti = ObjectProperty()
    abc = StringProperty('c')

    def __init__(self, **kwargs):
        super(TreeviewGroup, self).__init__(**kwargs)
        self.tv = TreeView(root_options=dict(text=""),
                       hide_root=False,
                       indent_level=4)
        for branch in tree:
            populate_tree_view(self.tv, None, branch)
        self.remove_widgets()
        self.treeview.add_widget(self.tv)

    def remove_widgets(self):
        for child in [child for child in self.treeview.children]:
            self.treeview.remove_widget(child)

    def filter(self, f):
        self.treeview.clear_widgets()
        self.tv = TreeView(root_options=dict(text=""),
                           hide_root=False,
                           indent_level=4)
        new_tree = []
        for n in tree:
            if f.lower() in n['node_id'].lower():
                new_tree.append(n)
        for branch in new_tree:
            populate_tree_view(self.tv, None, branch)

        self.treeview.add_widget(self.tv)

class CityScreen(Screen):
    groupName = ObjectProperty(None)
    popup = ObjectProperty(None)
    statecode = StringProperty('')

    def display_states(self, instance):
        if len(instance.text) > 0:
            if self.popup is None:
                self.popup = TreeviewGroup()
            self.popup.filter(instance.text)
            self.popup.open()

    def select_node(self, node):
        '''Select a node in the tree.
            '''

class MyApp(App):

    def build(self):
        self.root = Builder.load_file('demo.kv')
        return self.root

if __name__ == '__main__':
    MyApp().run()

demo.kv

#:kivy 1.10.0

<TreeViewLabel>:
    on_touch_down:
        app.root.stateName.text = self.text
        app.root.select_node(self)
        app.root.popup.dismiss()

<TestViewLabel>:
    on_touch_down:
        app.root.stateName.text = self.text
        app.root.select_node(self)
        app.root.popup.dismiss()

<TreeviewGroup>:
    id: treeview
    treeview: treeview
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False

    BoxLayout
        orientation: "vertical"
        TextInput:
            id: ti
            size_hint_y: .1
            text: root.abc
            on_text: root.filter(self.text)
        BoxLayout:
            id: treeview
            #on_press: root.select_node(self.text)
        Button:
            size_hint: 1, 0.1
            text: "Close"
            on_release: root.dismiss()

<CustomLabel@Label>:
    text_size: self.size
    valign: "middle"
    padding_x: 5

<SingleLineTextInput@TextInput>:
    multiline: False

<GreenButton@Button>:
    background_color: 1, 1, 1, 1
    size_hint_y: None
    height: self.parent.height * 0.150

CityScreen:
    stateName: stateName

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        CustomLabel:
            text: 'Text'

        SingleLineTextInput:
            id: stateName
            on_text: root.display_states(self)

        #Spinner:
            #text: "State Code"
            #values: ["111", "112", "113", "114"]
            #values: app.r
            #background_color: color_button if self.state == 'normal' else color_button_pressed
            #background_down: 'atlas://data/images/defaulttheme/spinner'
            #color: color_font
            #option_cls: Factory.get("MySpinnerOption")
            #size_hint: None, None

        GreenButton:
            text: 'Ok'
            on_press: root.insert_data(stateName.text)

        GreenButton:
            text: 'Cancel'
            on_press: app.stop()

        Label:

        Label:

When i type something in text TextBox then a pop up will be show.Then how to pass value from text TextBox to searchbox in pop up.

SearchBox working perfect for parent node.It's not working for child node.How will this work?

Body:
When i type something in text TextBox then a pop up will be show.Then how to pass value from text TextBox to searchbox in pop up like attached image.

Since you have the text input property in your popup when you open it you can pass the text:

...
<TreeviewGroup>:
    id: treeview
    treeview: treeview
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False
    ti: ti
    BoxLayout
        orientation: "vertical"
        TextInput:
            id: ti
            size_hint_y: .1
            on_text: root.filter(self.text)

then in the .py:

...

class CityScreen(Screen):
    groupName = ObjectProperty(None)
    popup = ObjectProperty(None)
    statecode = StringProperty('')

    def display_states(self, instance):
        if len(instance.text) > 0:
            if self.popup is None:
                self.popup = TreeviewGroup()
            self.popup.ti.text = instance.text
            self.popup.filter(instance.text)
            self.popup.open()
...

2 SearchBox working perfect for parent node.It's not working for child node.How will this work?

That was not very easy to do, that question deserved a bounty

To make a filter when the treeView has children that are also parents I do many recursion

first, add those functions to your .py

...
def get_children(n):
    '''get all the children in the node whithout her children'''
    if len(n['children']) == 0:
        return []
    else:
        children = [e['node_id'] for e in n['children']]
        for child in n['children']:
            children.extend([c for c in get_children(child)])
        return children

def get_children2(n, t):
    '''get the node with n as id'''
    if t is []:
        return False
    else:
        for child in t:
            if child['node_id'] == n:
                return child
            else:
                r = get_children2(n, child['children'])
                if r:
                    return r

def roots(n):
    '''return the roots (if a node have child it is a root)'''
    if len(n['children']) == 0:
        return [None]
    else:
        l = [n['node_id']]
        for c in n['children']:
            l.extend(roots(c))
        return l

def get_roots(t):
    '''this one is just to remove the None from the result of the first one'''
    fl = []
    for n in t:
        l = roots(n)
        li = []
        for e in l:
            if e is not None:
                li.append(e)
        fl.extend(li)
        if len(n['children']) == 0:
            fl.append(n['node_id'])
    return fl

...

Now you can change the filter method of the TreeView:

...
class TreeviewGroup(Popup):
    treeview = ObjectProperty(None)
    tv = ObjectProperty(None)
    ti = ObjectProperty()

    ...

    def filter(self, f):
        self.tv = TreeView(root_options=dict(text=""),
                           hide_root=False,
                           indent_level=4)
        for branch in tree:
            populate_tree_view(self.tv, None, branch)
        self.remove_widgets()
        self.treeview.add_widget(self.tv)
        l = []
        l_roots = get_roots(tree)
        dict_roots = []
        for node in self.tv.iterate_all_nodes():
            l.append(node)
        for i in range(len(l)):
            if l[i].text in l_roots:
                dict_roots.append({'ind': i, 'id': l[i].text})
        roots_childs = {}
        for e in l:
            try:
                nod = get_children2(e.text, tree)
                roots_childs[e.text] = get_children(nod)
            except TypeError:
                pass
        to_remove = []
        for e in roots_childs:
            for child in roots_childs[e]:
                if child not in l_roots:
                    if f.lower() not in child.lower():
                        if child not in to_remove:
                            to_remove.append(child)
            n = 0
            for child in roots_childs[e]:
                if child in to_remove:
                    n += 1
            if n == len(roots_childs[e]):
                if f.lower() not in e.lower():
                    to_remove.append(e)
        for n in l:
            if n.text in to_remove:
                self.tv.remove_node(n)

Update I have forgotten to add ti in the TreeViewGroop in the kv it's fixed now


来源: stackexchange

问:
too many imports cause `pub serve` to hang
When I run pub -v serve web for my AngularDart app, pub always hangs here:

```<code>% pub -v serve web
FINE: Pub 1.25.0-dev.16.4
FINE: Loading asset environment...
FINE: Initializing barback...
FINE: Serving packages on localhost:0.
MSG : Loading source assets...
FINE: Providing sources for ordreset|lib.
FINE: Loading source assets finished (0.053s).
FINE: Provided sources.
FINE: Loading transformers...
FINE: Transformer dependencies:
    | angular: -
    | test/pub_serve: -
    | dart_to_js_script_rewriter: -
FINE: Using cached transformer snapshot.
MSG : Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers...
FINE: Loading transformers from [angular, test/pub_serve, dart_to_js_script_rewriter]
FINE: Spawning isolate from ./.pub/transformers/transformers.snapshot.
FINE: Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers finished (0.151s).
FINE: Transformers from angular: {group of [[BuilderTransformer: Instance of 'TemplatePlaceholderBuilder'], [ReflectionRemover], [StylesheetCompiler, BuilderTransformer: Instance of 'LibraryBuilder']]}
FINE: Transformers from test/pub_serve: {PubServe}
FINE: Transformers from dart_to_js_script_rewriter: {DartToJsScriptRewriter}
FINE: Loading transformers finished (0.649s).
FINE: Initializing barback finished (0.763s).
FINE: Loading asset environment finished (1.062s).
FINE: Providing sources for ordreset|web.
FINE: Bound "web" to localhost:8080.
MSG : Serving ordreset web on http://localhost:8080
FINE: [Fine from StylesheetCompiler]:
    | [processStylesheet] took 50 ms on ordreset|lib/src/dashboard_component.css
FINE: [Fine from StylesheetCompiler on ordreset|lib/src/dashboard_component.css]:
    | Took 0.2s (0.0s awaiting secondary inputs).
FINE: [Fine from StylesheetCompiler]:
    | [processStylesheet] took 30 ms on ordreset|web/main.css
FINE: [Fine from StylesheetCompiler on ordreset|web/main.css]:
    | Took 0.2s (0.0s awaiting secondary inputs).
FINE: [Fine from BuilderTransformer: Instance of 'TemplatePlaceholderBuilder' on ordreset|primary]:
    | Took 0.4s (0.0s awaiting secondary inputs).
FINE: [Fine from BuilderTransformer: Instance of 'LibraryBuilder' on ordreset|primary]:
    | Not yet complete after 10.0s
FINE: [Fine from BuilderTransformer: Instance of 'LibraryBuilder' on ordreset|primary]:
    | Not yet complete after 20.0s
</code>```

I noticed that when removing all import 'package:xml/xml.dart' as xml; statements, that pub serve doesn't hang anymore then. But I did observe the same behaviour in the past, that removing all import 'package:angular_components/angular_components.dart'; fixed the problem as well. Hence I actually doubt that it's a problem with either the xml or the angular_components package but that the problem might be related to an import limitation of source_gen, similar to this issue from the past.

I've uploaded my AngularDart project here. You can run pub get and then pub -v serve web yourself to see how pub hangs.

PS: I've emptied all AngularDart HTML template files before pushing the code to the public GitHub repo for privacy reasons but that shouldn't change the fact that pub serve should still succeed.

答:
As @GünterZöchbauer pointed out in a comment of his answer, following the steps below solves the problem:

Remove .pub in your project folder.

Run pub get --no-precompile instead of a regular pub get to prevent precompiling which seems to cause the problem.

Now run pub serve as usual.

ContentLicense: CC BY-SA 3.0

Body:
When I run pub -v serve web for my AngularDart app, pub always hangs here:

% pub -v serve web
FINE: Pub 1.25.0-dev.16.4
FINE: Loading asset environment...
FINE: Initializing barback...
FINE: Serving packages on localhost:0.
MSG : Loading source assets...
FINE: Providing sources for ordreset|lib.
FINE: Loading source assets finished (0.053s).
FINE: Provided sources.
FINE: Loading transformers...
FINE: Transformer dependencies:
    | angular: -
    | test/pub_serve: -
    | dart_to_js_script_rewriter: -
FINE: Using cached transformer snapshot.
MSG : Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers...
FINE: Loading transformers from [angular, test/pub_serve, dart_to_js_script_rewriter]
FINE: Spawning isolate from ./.pub/transformers/transformers.snapshot.
FINE: Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers finished (0.151s).
FINE: Transformers from angular: {group of [[BuilderTransformer: Instance of 'TemplatePlaceholderBuilder'], [ReflectionRemover], [StylesheetCompiler, BuilderTransformer: Instance of 'LibraryBuilder']]}
FINE: Transformers from test/pub_serve: {PubServe}
FINE: Transformers from dart_to_js_script_rewriter: {DartToJsScriptRewriter}
FINE: Loading transformers finished (0.649s).
FINE: Initializing barback finished (0.763s).
FINE: Loading asset environment finished (1.062s).
FINE: Providing sources for ordreset|web.
FINE: Bound "web" to localhost:8080.
MSG : Serving ordreset web on http://localhost:8080
FINE: [Fine from StylesheetCompiler]:
    | [processStylesheet] took 50 ms on ordreset|lib/src/dashboard_component.css
FINE: [Fine from StylesheetCompiler on ordreset|lib/src/dashboard_component.css]:
    | Took 0.2s (0.0s awaiting secondary inputs).
FINE: [Fine from StylesheetCompiler]:
    | [processStylesheet] took 30 ms on ordreset|web/main.css
FINE: [Fine from StylesheetCompiler on ordreset|web/main.css]:
    | Took 0.2s (0.0s awaiting secondary inputs).
FINE: [Fine from BuilderTransformer: Instance of 'TemplatePlaceholderBuilder' on ordreset|primary]:
    | Took 0.4s (0.0s awaiting secondary inputs).
FINE: [Fine from BuilderTransformer: Instance of 'LibraryBuilder' on ordreset|primary]:
    | Not yet complete after 10.0s
FINE: [Fine from BuilderTransformer: Instance of 'LibraryBuilder' on ordreset|primary]:
    | Not yet complete after 20.0s

I noticed that when removing all import 'package:xml/xml.dart' as xml; statements, that pub serve doesn't hang anymore then. But I did observe the same behaviour in the past, that removing all import 'package:angular_components/angular_components.dart'; fixed the problem as well. Hence I actually doubt that it's a problem with either the xml or the angular_components package but that the problem might be related to an import limitation of source_gen, similar to this issue from the past.

I've uploaded my AngularDart project here. You can run pub get and then pub -v serve web yourself to see how pub hangs.

PS: I've emptied all AngularDart HTML template files before pushing the code to the public GitHub repo for privacy reasons but that shouldn't change the fact that pub serve should still succeed.


问:
Resizing font to fit the current screen size on a website
If I have a font set to a particular size for a desktop screen, can I reduce it using CSS3 @media Rule to also fit well in Mobile devices?

I have this line of code below:

```<code><style>
@media only screen and (min-device-width: 150px) {
.log {font-size: 10px}
}
</style>

<body>
<div class="log" style="font-size: 35px;">
HEADER TEXT<br />
</div>
</body>
</code>```

But it is not responsive when I open the site on my mobile device!!! What am I doing wrong???

答:
You have set the media query wrong. It specifies font-size to devices with width higher than 150px. You should use max-width in your media query. What that does is applies the desired css to device up to that width.
For example :

```<code>@media only screen and (max-device-width: 920px) {
.log {font-size: 10px}
}
</code>```

This will apply font-size: 10px to devices with width below 920px.
And using inline styles will override css from your css file or style tag. So, avoid doing that and write all your css in css file or style tag.
I hope this answers your question.

Body:
If I have a font set to a particular size for a desktop screen, can I reduce it using CSS3 @media Rule to also fit well in Mobile devices?

I have this line of code below:

HEADER TEXT

But it is not responsive when I open the site on my mobile device!!! What am I doing wrong???

Body:
You have set the media query wrong. It specifies font-size to devices with width higher than 150px. You should use max-width in your media query. What that does is applies the desired css to device up to that width.
For example :

@media only screen and (max-device-width: 920px) {
.log {font-size: 10px}
}

This will apply font-size: 10px to devices with width below 920px.
And using inline styles will override css from your css file or style tag. So, avoid doing that and write all your css in css file or style tag.
I hope this answers your question.


问:
Excel Macro VBA Scrolling up not working
my current sheet has rows 1-11 as a frozen pane, and 12 to 12.end(xldown) as an autofilter. whenever a filter is applied and my focus is on a much higher row (say row 100), my list looks short due to the fact my screen isn't scrolling all the way up to reveal the full autofilter. I know the easy solution is just to push up on my mouses scroll wheel, but this file isn't just for me.

Looking for a code that will snap the focus to the top(first) row of my autofilter.

Ive tried:

```<code>range("c12").select;
range("c12").activate;
range("c11").cells(1,0).select;
range("c11").cells(1,0).activate;
activewindow.scrollrow = 1;
activewindow.scrollrow = 12;
</code>```

and none work. not sure what to try anymore. any ideas?

Image of spreadsheet

答:
Try this

```<code>ActiveWindow.SmallScroll down:=1  ' or any number to get what you want
</code>```

I agree with @Corrosive 2, you souldn't have semi-colons

Body:
my current sheet has rows 1-11 as a frozen pane, and 12 to 12.end(xldown) as an autofilter. whenever a filter is applied and my focus is on a much higher row (say row 100), my list looks short due to the fact my screen isn't scrolling all the way up to reveal the full autofilter. I know the easy solution is just to push up on my mouses scroll wheel, but this file isn't just for me.

Looking for a code that will snap the focus to the top(first) row of my autofilter.

Ive tried:

range("c12").select;
range("c12").activate;
range("c11").cells(1,0).select;
range("c11").cells(1,0).activate;
activewindow.scrollrow = 1;
activewindow.scrollrow = 12;

and none work. not sure what to try anymore. any ideas?

Image of spreadsheet

Body:
Try this

ActiveWindow.SmallScroll down:=1  ' or any number to get what you want

I agree with @Corrosive 2, you souldn't have semi-colons


问:
How can I change a variable in Jekyll _config.yml dynamically?
Hi I'm working on a Jekyll project and I need to put a variable in _config.yml that I want to change dynamically from the template code.

This is what I want to do, but I can't get it to work. Is it possible to do this?

In _config.yml:

```<code>my_var: "value"
</code>```

In template.html:

```<code>{% site.my_var = "newvalue" %}

{% case site.my_var %}
  {% when "value" %}
    //do this
  {% when "newvalue" %}
   //do this instead
{% endcase %}
</code>```

答:
While you apparently cannot use Liquid conditionals nor Environment Variables (as in many other build scripts), you can do a selective overrides with a second yml file:

```<code>$> bundle exec jekyll serve --drafts --incremental --config _config.yml,_dev.yml
</code>```

with a _dev.yml:

```<code># overrides title in _config.yml
title: "My Website (dev mode)"

# see my styles uncompressed for dev work
sass:
    style: uncompressed
</code>```

Perhaps that fits your needs...

Body:
Hi I'm working on a Jekyll project and I need to put a variable in _config.yml that I want to change dynamically from the template code.

This is what I want to do, but I can't get it to work. Is it possible to do this?

In _config.yml:

my_var: "value"

In template.html:

{% site.my_var = "newvalue" %}

{% case site.my_var %}
  {% when "value" %}
    //do this
  {% when "newvalue" %}
   //do this instead
{% endcase %}

Body:
While you apparently cannot use Liquid conditionals nor Environment Variables (as in many other build scripts), you can do a selective overrides with a second yml file:

$> bundle exec jekyll serve --drafts --incremental --config _config.yml,_dev.yml

with a _dev.yml:

# overrides title in _config.yml
title: "My Website (dev mode)"

# see my styles uncompressed for dev work
sass:
    style: uncompressed

Perhaps that fits your needs...


问:
Scala expression to replace a file extension in a string
Here is a version I wrote using split:

```<code>fileName.split('.').init ++ Seq("js") mkString "."
</code>```

This transforms e.g. foo.bar.coffee into foo.bar.js.

What I like:

it works

it doesn't rely on things like indexOf()

it feels functional ;)

What I don't like:

it's not as short as I would hope

it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those

another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background

a slightly shorter syntax for the original approach (corner cases not covered) reads:

fileName.split('.').init :+ "js" mkString "."

答:
So, I'll go for speed here. As it happens, substring is constant time because it simply does not copy the string. So,

```<code>((index: Int) => (
) + ".js")(fileName lastIndexOf '.')
</code>```

This uses a closure, which will slow it down a bit. Faster:

```<code>def addJS(fileName: String) = {
    def addJSAt(index: Int) = (
        if (index >= 0) fileName substring (0, index)
        else fileName
    ) + ".js"

    addJSAt(fileName lastIndexOf '.')
}
</code>```

EDIT: As it happens, Java now does copy the string on substring.

ContentLicense: CC BY-SA 2.5

Body:
Here is a version I wrote using split:

fileName.split('.').init ++ Seq("js") mkString "."

This transforms e.g. foo.bar.coffee into foo.bar.js.

What I like:

it works

it doesn't rely on things like indexOf()

it feels functional ;)

What I don't like:

it's not as short as I would hope

it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those

another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background

a slightly shorter syntax for the original approach (corner cases not covered) reads:

fileName.split('.').init :+ "js" mkString "."

Body:
So, I'll go for speed here. As it happens, substring is constant time because it simply does not copy the string. So,

((index: Int) => (
) + ".js")(fileName lastIndexOf '.')

This uses a closure, which will slow it down a bit. Faster:

def addJS(fileName: String) = {
    def addJSAt(index: Int) = (
        if (index >= 0) fileName substring (0, index)
        else fileName
    ) + ".js"

    addJSAt(fileName lastIndexOf '.')
}

EDIT: As it happens, Java now does copy the string on substring.


问:
ORM for google App Engine (java)
I developed google endpoints API's & access cloud sql database by using JDBC.now I want to use ORM tool for accessing cloud sql database.
so which ORM tools are supported by google app engine rather that JDO & JPA?
I mean,does hibernate support GAE?</p>

答:
Yes, Google App Engine supports Hibernate ORM in combination with Google Cloud SQL.
We're using this combination in almost all of our Google App Engine projects, sometimes even with connection pooling;

Can i use HikariCP on Google App Engine

Cloud SQL can even be used during development;

Using Google Cloud SQL during Java appengine development (instead of local MySQL instance)

For the Hibernate connection we've implemented our own ConnectionProvider (i got this idea from appengine-java-connection-pool). In persistence.xml

With BasicConnectionProvider;

```<code>public class BasicConnectionProvider implements ConnectionProvider, Configurable, Stoppable
{
    private static final long serialVersionUID = 5535849343546193022L;
    private static final org.jboss.logging.Logger LOGGER = org.jboss.logging.Logger.getLogger(com.project.server.hibernate.BasicConnectionProvider.class);
    private DriverManagerDataSource mDriverManagerDataSource = null;

    private int mConnectionCount;

    // *************************************************************************
    // Configurable
    // *************************************************************************

    @SuppressWarnings("rawtypes")
    @Override
    public void configure(Map pProperties) throws HibernateException
    {
        try
        {
            LOGGER.debug("Configuring DataSource");

            DriverManagerDataSource lDriverManagerDataSource = new DriverManagerDataSource();

            if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production)
            {
                lDriverManagerDataSource.setDriverClassName("com.mysql.jdbc.GoogleDriver");
                lDriverManagerDataSource.setUrl("jdbc:google:mysql://appengine-id:europe-west1:project/project");
            }
            else
            {
                lDriverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
                lDriverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/project");
            }

            lDriverManagerDataSource.setUsername("root");
            lDriverManagerDataSource.setPassword("password");

            Properties lProperties = loadConfiguration(pProperties);

            lProperties.put("useSSL", "false");
            lProperties.put("cachePrepStmts", "true");
            lProperties.put("useServerPrepStmts", "true");
            lProperties.put("prepStmtCacheSize", "500");
            lProperties.put("prepStmtCacheSqlLimit", "2048");

            lDriverManagerDataSource.setConnectionProperties(lProperties);

            setDriverManagerDataSource(lDriverManagerDataSource);

            mConnectionCount = 0;
        }
        catch (Exception e)
        {
            throw new HibernateException(e);
        }

        LOGGER.debug("DataSource Configured");
    }

    public static Properties loadConfiguration(Map props)
    {
        Properties lProperties = new Properties();

        copyProperty(AvailableSettings.ISOLATION, props, "transactionIsolation", lProperties);
        copyProperty(AvailableSettings.AUTOCOMMIT, props, "autoCommit", lProperties);
        copyProperty(AvailableSettings.DRIVER, props, "driverClassName", lProperties);
        copyProperty(AvailableSettings.URL, props, "jdbcUrl", lProperties);
        copyProperty(AvailableSettings.USER, props, "username", lProperties);
        copyProperty(AvailableSettings.PASS, props, "password", lProperties);

        return lProperties;
    }

    @SuppressWarnings("rawtypes")
    private static void copyProperty(String srcKey, Map src, String dstKey, Properties dst)
    {
        if (src.containsKey(srcKey))
        {
            dst.setProperty(dstKey, (String) src.get(srcKey));
        }
    }

    // *************************************************************************
    // ConnectionProvider
    // *************************************************************************

    @Override
    public Connection getConnection() throws SQLException
    {
        Connection lConnection = null;

        if (mDriverManagerDataSource != null)
        {
            lConnection = mDriverManagerDataSource.getConnection();
        }

        mConnectionCount++;
        return lConnection;
    }

    @Override
    public void closeConnection(Connection pConnection) throws SQLException
    {
        mConnectionCount--;
        pConnection.close();
    }

    @Override
    public boolean supportsAggressiveRelease()
    {
        return false;
    }

    @Override
    @SuppressWarnings("rawtypes")
    public boolean isUnwrappableAs(Class unwrapType)
    {
        return ConnectionProvider.class.equals(unwrapType)
                || com.project.server.hibernate.BasicConnectionProvider.class.isAssignableFrom(unwrapType)
                || DataSource.class.isAssignableFrom(unwrapType);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T unwrap(Class<T> unwrapType)
    {
        if (ConnectionProvider.class.equals(unwrapType) ||
                com.project.server.hibernate.BasicConnectionProvider.class.isAssignableFrom(unwrapType))
        {
            return (T) this;
        }
        else if (DataSource.class.isAssignableFrom(unwrapType))
        {
            return (T) mDriverManagerDataSource;
        }
        else
        {
            throw new UnknownUnwrapTypeException(unwrapType);
        }
    }

    // *************************************************************************
    // Stoppable
    // *************************************************************************

    @Override
    public void stop()
    {

    }

    public DriverManagerDataSource getDriverManagerDataSource()
    {
        return mDriverManagerDataSource;
    }

    public void setDriverManagerDataSource(DriverManagerDataSource pDriverManagerDataSource)
    {
        mDriverManagerDataSource = pDriverManagerDataSource;
    }
}
</code>```

Title: ORM for google App Engine (java)

Body:
Yes, Google App Engine supports Hibernate ORM in combination with Google Cloud SQL.
We're using this combination in almost all of our Google App Engine projects, sometimes even with connection pooling;

Can i use HikariCP on Google App Engine

Cloud SQL can even be used during development;

Using Google Cloud SQL during Java appengine development (instead of local MySQL instance)

For the Hibernate connection we've implemented our own ConnectionProvider (i got this idea from appengine-java-connection-pool). In persistence.xml

With BasicConnectionProvider;

public class BasicConnectionProvider implements ConnectionProvider, Configurable, Stoppable
{
    private static final long serialVersionUID = 5535849343546193022L;
    private static final org.jboss.logging.Logger LOGGER = org.jboss.logging.Logger.getLogger(com.project.server.hibernate.BasicConnectionProvider.class);
    private DriverManagerDataSource mDriverManagerDataSource = null;

    private int mConnectionCount;

    // *************************************************************************
    // Configurable
    // *************************************************************************

    @SuppressWarnings("rawtypes")
    @Override
    public void configure(Map pProperties) throws HibernateException
    {
        try
        {
            LOGGER.debug("Configuring DataSource");

            DriverManagerDataSource lDriverManagerDataSource = new DriverManagerDataSource();

            if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production)
            {
                lDriverManagerDataSource.setDriverClassName("com.mysql.jdbc.GoogleDriver");
                lDriverManagerDataSource.setUrl("jdbc:google:mysql://appengine-id:europe-west1:project/project");
            }
            else
            {
                lDriverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
                lDriverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/project");
            }

            lDriverManagerDataSource.setUsername("root");
            lDriverManagerDataSource.setPassword("password");

            Properties lProperties = loadConfiguration(pProperties);

            lProperties.put("useSSL", "false");
            lProperties.put("cachePrepStmts", "true");
            lProperties.put("useServerPrepStmts", "true");
            lProperties.put("prepStmtCacheSize", "500");
            lProperties.put("prepStmtCacheSqlLimit", "2048");

            lDriverManagerDataSource.setConnectionProperties(lProperties);

            setDriverManagerDataSource(lDriverManagerDataSource);

            mConnectionCount = 0;
        }
        catch (Exception e)
        {
            throw new HibernateException(e);
        }

        LOGGER.debug("DataSource Configured");
    }

    public static Properties loadConfiguration(Map props)
    {
        Properties lProperties = new Properties();

        copyProperty(AvailableSettings.ISOLATION, props, "transactionIsolation", lProperties);
        copyProperty(AvailableSettings.AUTOCOMMIT, props, "autoCommit", lProperties);
        copyProperty(AvailableSettings.DRIVER, props, "driverClassName", lProperties);
        copyProperty(AvailableSettings.URL, props, "jdbcUrl", lProperties);
        copyProperty(AvailableSettings.USER, props, "username", lProperties);
        copyProperty(AvailableSettings.PASS, props, "password", lProperties);

        return lProperties;
    }

    @SuppressWarnings("rawtypes")
    private static void copyProperty(String srcKey, Map src, String dstKey, Properties dst)
    {
        if (src.containsKey(srcKey))
        {
            dst.setProperty(dstKey, (String) src.get(srcKey));
        }
    }

    // *************************************************************************
    // ConnectionProvider
    // *************************************************************************

    @Override
    public Connection getConnection() throws SQLException
    {
        Connection lConnection = null;

        if (mDriverManagerDataSource != null)
        {
            lConnection = mDriverManagerDataSource.getConnection();
        }

        mConnectionCount++;
        return lConnection;
    }

    @Override
    public void closeConnection(Connection pConnection) throws SQLException
    {
        mConnectionCount--;
        pConnection.close();
    }

    @Override
    public boolean supportsAggressiveRelease()
    {
        return false;
    }

    @Override
    @SuppressWarnings("rawtypes")
    public boolean isUnwrappableAs(Class unwrapType)
    {
        return ConnectionProvider.class.equals(unwrapType)
                || com.project.server.hibernate.BasicConnectionProvider.class.isAssignableFrom(unwrapType)
                || DataSource.class.isAssignableFrom(unwrapType);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T unwrap(Class<T> unwrapType)
    {
        if (ConnectionProvider.class.equals(unwrapType) ||
                com.project.server.hibernate.BasicConnectionProvider.class.isAssignableFrom(unwrapType))
        {
            return (T) this;
        }
        else if (DataSource.class.isAssignableFrom(unwrapType))
        {
            return (T) mDriverManagerDataSource;
        }
        else
        {
            throw new UnknownUnwrapTypeException(unwrapType);
        }
    }

    // *************************************************************************
    // Stoppable
    // *************************************************************************

    @Override
    public void stop()
    {

    }

    public DriverManagerDataSource getDriverManagerDataSource()
    {
        return mDriverManagerDataSource;
    }

    public void setDriverManagerDataSource(DriverManagerDataSource pDriverManagerDataSource)
    {
        mDriverManagerDataSource = pDriverManagerDataSource;
    }
}


问:
TypeError: byte indices must be integers
I want to get the top artists from a specific country from the last fm API in JSON and save the name and url in the name and url variables. But it always appears "TypeError: byte indices must be integers". Do you know where is the issue?

Working example:

```<code>import requests

api_key = "xxx"

for i in range(2,5):

    artists = requests.get('http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&page='+str(i)+'&api_key='+api_key)
    for artist in artists:

        print(artist)

        #name = artist['topartists']['artist']['name']
        #url  = artist['topartists']['artist']['url']
</code>```

答:
You want:

```<code>response = requests.get(...)
data = response.json()
for artist in data["topartists"]["artist"]:
    name = artist["name"]
    # etc
</code>```

Explanation: requests.get() returns a response object. Iterating over the response object is actually iterating over the raw textual response content, line by line. Since this content is actually json, you want to first decode it to Python (response.json() is mainly a shortcut for json.loads(response.content)). You then get a python dict with, in this case, a single key "topartists" which points to a list of "artist" dicts.

A couple hints:

First you may want to learn to use string formatting instead of string concatenation. This :

```<code>'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&page='+str(i)+'&api_key='+api_key
</code>```

is ugly and hardly readable. Using string formatting:

```<code>urltemplate = "http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&page={page}&api_key={api_key}"
url = urltemplate.format(page=i, api_key=api_key)
</code>```

but actually requests knows how to build a querystring from a dict, so you should really use this instead:

```<code>query = {
    "method": "geo.gettopartists",
    "country":"spain",
    "format":"json",
    "api_key": api_key
    }

url = "http://ws.audioscrobbler.com/2.0/"
for pagenum in range(x, y):
    query["page"] = pagenum
    response = requests.get(url, params=query)
    # etc
</code>```

Then, you may also want to handle errors - there are quite a few things that can go wrong doing an HTTP request.

Body:
I want to get the top artists from a specific country from the last fm API in JSON and save the name and url in the name and url variables. But it always appears "TypeError: byte indices must be integers". Do you know where is the issue?

Working example:

import requests

api_key = "xxx"

for i in range(2,5):

    artists = requests.get('http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&page='+str(i)+'&api_key='+api_key)
    for artist in artists:

        print(artist)

        #name = artist['topartists']['artist']['name']
        #url  = artist['topartists']['artist']['url']

Body:
You want:

response = requests.get(...)
data = response.json()
for artist in data["topartists"]["artist"]:
    name = artist["name"]
    # etc

Explanation: requests.get() returns a response object. Iterating over the response object is actually iterating over the raw textual response content, line by line. Since this content is actually json, you want to first decode it to Python (response.json() is mainly a shortcut for json.loads(response.content)). You then get a python dict with, in this case, a single key "topartists" which points to a list of "artist" dicts.

A couple hints:

First you may want to learn to use string formatting instead of string concatenation. This :

'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&page='+str(i)+'&api_key='+api_key

is ugly and hardly readable. Using string formatting:

urltemplate = "http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&page={page}&api_key={api_key}"
url = urltemplate.format(page=i, api_key=api_key)

but actually requests knows how to build a querystring from a dict, so you should really use this instead:

query = {
    "method": "geo.gettopartists",
    "country":"spain",
    "format":"json",
    "api_key": api_key
    }

url = "http://ws.audioscrobbler.com/2.0/"
for pagenum in range(x, y):
    query["page"] = pagenum
    response = requests.get(url, params=query)
    # etc

Then, you may also want to handle errors - there are quite a few things that can go wrong doing an HTTP request.


问:
local xml parsing in android

Possible Duplicate:

  Parsing local xml file in android

Hi every one, In this folowing link there is a xml parser

http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser/#idc-cover

instead of using
url can i use the xml file stored locally, means inside "res/xml/*.xml"
can any one provide me a code for dat...(am brand new to android, pls help me)

答: Refer this Question Parsing local XML file using Sax in Android</p>

Title: local xml parsing in android


答:
The inline styling of the element is overriding the media query. Try this instead:

.log {
font-size: 35px;
}

@media only screen and (min-device-width: 150px) {
.log {font-size: 10px}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div class="log">
HEADER TEXT<br />
</div>
</body></code>```

Title: Resizing font to fit the current screen size on a website

Body:
The inline styling of the element is overriding the media query. Try this instead:

.log {
font-size: 35px;
}

@media only screen and (min-device-width: 150px) {
.log {font-size: 10px}
}

<body>
<div class="log">
HEADER TEXT<br />
</div>
</body>


问:
One line bash command to find N oldest and newest files in a directory
I have the following command:

```<code>files=$(ls -lhrt dirname) && echo $files | head -5 && echo $files | tail -5
</code>```

The idea is to return the oldest and newest 5 files in a directory dirname. This returns the requested data - however, the lines are jumbled together.

Is there a way to better format the output? (or perhaps a better way to write this functionality)?

答:
Always quote variable expansions to prevent word splitting and globbing. When you leave $files unquoted bash's word splitting pass causes the newlines to be lost.

```<code>files=$(ls -lhrt dirname) && echo "$files" | head -5 && echo "$files" | tail -5
</code>```

There's no real benefit from using the && operators. I'd just write:

```<code>files=$(ls -lhrt dirname)
echo "$files" | head -5
echo "$files" | tail -5
</code>```

Or, better, swap the echos for <<< to avoid unnecessary subprocesses.

```<code>files=$(ls -lhrt dirname)
head -5 <<< "$files"
tail -5 <<< "$files"
</code>```

Body:
I have the following command:

files=$(ls -lhrt dirname) && echo $files | head -5 && echo $files | tail -5

The idea is to return the oldest and newest 5 files in a directory dirname. This returns the requested data - however, the lines are jumbled together.

Is there a way to better format the output? (or perhaps a better way to write this functionality)?

Body:
Always quote variable expansions to prevent word splitting and globbing. When you leave $files unquoted bash's word splitting pass causes the newlines to be lost.

files=$(ls -lhrt dirname) && echo "$files" | head -5 && echo "$files" | tail -5

There's no real benefit from using the && operators. I'd just write:

files=$(ls -lhrt dirname)
echo "$files" | head -5
echo "$files" | tail -5

Or, better, swap the echos for <<< to avoid unnecessary subprocesses.

files=$(ls -lhrt dirname)
head -5 <<< "$files"
tail -5 <<< "$files"


问:
How to invoke AWS lambda function from another lambda function and return without waitng for the called lambda result
I am having two AWS lambda java 8 function "lambda A" and "lambda B". "lambda A" function invokes "lambda B" function and waits till it gets the result of "lambda B". But I want to invoke the "lambda B" and return the "lambda A" function immediately. Is it possible to implement and any reference links related to it.</p>

答:
With the AWS Lambda SDK for Java you can set the InvocationType within the InvokeRequest object. This will just invoke your function, but won't wait for a response.

From the Javadocs:

By default, the Invoke API assumes RequestResponse invocation type. You can optionally request asynchronous execution by specifying Event as the InvocationType.

Example:

```<code>AWSLambda lambdaClient = AWSLambdaClientBuilder.defaultClient();
InvokeRequest request = new InvokeRequest();
request.withFunctionName(name)
       .withInvocationType(InvocationType.Event)
       .withPayload(payload);
InvokeResult result = lambdaClient.invoke(request);
</code>```

Please also consider reading this and this question.

ContentLicense: CC BY-SA 4.0

Body:
With the AWS Lambda SDK for Java you can set the InvocationType within the InvokeRequest object. This will just invoke your function, but won't wait for a response.

From the Javadocs:

By default, the Invoke API assumes RequestResponse invocation type. You can optionally request asynchronous execution by specifying Event as the InvocationType.

Example:

AWSLambda lambdaClient = AWSLambdaClientBuilder.defaultClient();
InvokeRequest request = new InvokeRequest();
request.withFunctionName(name)
       .withInvocationType(InvocationType.Event)
       .withPayload(payload);
InvokeResult result = lambdaClient.invoke(request);

Please also consider reading this and this question.


问:
How to change the cart button links on menu?
I want to change the links of cart button on the menu.

For now I activated "WooCommerce Menu Cart" plugin and using storefront theme.

I googled and tried this one.

```<code>/**
 * Set a custom add to cart URL to redirect to
 * @return string
 */
function custom_add_to_cart_redirect() {
    return 'http://www.yourdomain.com/your-page/';
}
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect' );
</code>```

But this work for only "view cart" buttons on pages.

What I want is to change the menu cart link url to something like this.

From

```<code>http://mydomain.name/cart
</code>```

To

```<code>http://mydomain.name/custom_cart_page
</code>```

答: If it only changes the url on the same domain, you just need to edit (the cart page) then change the slug.</p>

Body:
I want to change the links of cart button on the menu.

For now I activated "WooCommerce Menu Cart" plugin and using storefront theme.

I googled and tried this one.

/**
 * Set a custom add to cart URL to redirect to
 * @return string
 */
function custom_add_to_cart_redirect() {
    return 'http://www.yourdomain.com/your-page/';
}
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect' );

But this work for only "view cart" buttons on pages.

What I want is to change the menu cart link url to something like this.

From

http://mydomain.name/cart

To

http://mydomain.name/custom_cart_page


问:
Multiple line user input in Python
I want to know how to write an input that accepts a string with multiple lines, so I can run code on that string. (In Python 3.6)

My code is so far like this:

```<code>inp = input()

def isVowel(c):

    """
    Pré-condições: Receber um carácter para analisar
    Pós-Condições: checar se é ou não uma vogal
    """

    if(c in 'aeiouáéíóúàèìòùãõâêîôûAEIOUÁÉÍÓÚÀÈÌÒÙÃÕÂÊÎÔÛ'):
        return True
    return False

def eraseVowels(string):

    """
    Pré-condições: Recebe um string
    Pós-Condições: Eliminar as vogais
    """

    new_str = ''
    for c in eraseExtraBlanks(string):
        if not isVowel(c):
            new_str += c
    return new_str

def eraseExtraBlanks(string):

    """
    Pré-condições: Recebe uma string como input
    Pós-Condições: eliminação dos espaços supérfluos
    """

    string = string.replace('  ',' ')
    if('  ' in string):
        return eraseExtraBlanks(string)
    return string.strip()

print(eraseExtraBlanks(eraseVowels(inp)))
</code>```

答:
I Think This Is Helpful For You</p>

```<code>print("give the input here ")
contents = []
while True:
try:
    line = input()
except EOFError:
    break
contents.append(line)
</code>```

Title: Multiple line user input in Python

Body:
I want to know how to write an input that accepts a string with multiple lines, so I can run code on that string. (In Python 3.6)

My code is so far like this:

inp = input()

def isVowel(c):

    """
    Pré-condições: Receber um carácter para analisar
    Pós-Condições: checar se é ou não uma vogal
    """

    if(c in 'aeiouáéíóúàèìòùãõâêîôûAEIOUÁÉÍÓÚÀÈÌÒÙÃÕÂÊÎÔÛ'):
        return True
    return False

def eraseVowels(string):

    """
    Pré-condições: Recebe um string
    Pós-Condições: Eliminar as vogais
    """

    new_str = ''
    for c in eraseExtraBlanks(string):
        if not isVowel(c):
            new_str += c
    return new_str

def eraseExtraBlanks(string):

    """
    Pré-condições: Recebe uma string como input
    Pós-Condições: eliminação dos espaços supérfluos
    """

    string = string.replace('  ',' ')
    if('  ' in string):
        return eraseExtraBlanks(string)
    return string.strip()

print(eraseExtraBlanks(eraseVowels(inp)))

Body:
I Think This Is Helpful For You

print("give the input here ")
contents = []
while True:
try:
    line = input()
except EOFError:
    break
contents.append(line)


问:
SpringBoot RestTemplate ignores spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false
I am working with OffsetDateTime objects.

I want to output this type in ISO format so I've added the aforementioned property to my application.yml and it works fine when I use it in my controller.

```<code>@JsonInclude(JsonInclude.Include.NON_NULL)
public class Schedule
{
    private OffsetDateTime time;
    private String mode;
}
</code>```

Using in my controller:

```<code>public ResponseEntity taskManagerTest() {
    Schedule bpTaskManagerRequest = new Schedule();

    return ResponseEntity.status(HttpStatus.CREATED).headers(null).body(bpTaskManagerRequest);
}
</code>```

Example result when I am returning my object:

```<code>{
  "time": "2017-11-12T15:03:05.171Z",
  "mode": "eSetTime"
}
</code>```

But if I use the same object to send it further using RestTemplate in my Spring service:

```<code>    HttpEntity<Schedule> httpEntity = new HttpEntity<>(bpTaskManagerRequest, headers);

    ResponseEntity<String> answer = restTemplate.exchange(bpTaskManagerURL, HttpMethod.POST, httpEntity,
            String.class);
</code>```

It is serialized as:

```<code>{
    "time": 1510498985.171000000,
    "mode": "eSetTime"
}
</code>```

My RestTemplate is defined as:

```<code>@Autowired
private RestTemplate restTemplate;
</code>```

application.yml snippet:

```<code>spring:
    jackson:
        serialization:
            write-dates-as-timestamps: false
</code>```

build.gradle snippet:

```<code>buildscript {
    ext {
        springBootVersion = '1.5.4.RELEASE'
        ext.kotlin_version = '1.1.51'
    }
}
compile('com.fasterxml.jackson.module:jackson-module-parameter-names')
compile('com.fasterxml.jackson.datatype:jackson-datatype-jdk8')
compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310')
</code>```

Example project: https://github.com/deepres/OffsetDateTime-with-RestTemplate

答:
Your application is creating its own RestTemplate bean and not applying any customisation to it. This means that it will be use the default message converters and default Jackson configuration, rather than anything that's configured by Spring Boot.

As described in the reference documentation, Spring Boot provides a RestTemplateBuilder that can be used to create a RestTemplate. It "will ensure that sensible HttpMessageConverters are applied to RestTemplate instances". You can update your example to use it by changing WebConfiguration to the following:

```<code>package com.example.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;

@Configuration
public class WebConfiguration {

    @Bean
    public RestTemplate getRestTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

}
</code>```

With this change in place, the conversion is now consistent:

```<code>2017-11-17 12:35:02.892  INFO 28527 --- [nio-8080-exec-2] com.example.demo.ExampleController       : Rest template: {"label":"test from controller","time":"2017-11-17T12:35:02.821Z"}
2017-11-17 12:35:02.905  INFO 28527 --- [nio-8080-exec-1] com.example.demo.DemoService             : Object mapper:{"label":"test from controller","time":"2017-11-17T12:35:02.821Z"}
</code>```

Body:
I am working with OffsetDateTime objects.

I want to output this type in ISO format so I've added the aforementioned property to my application.yml and it works fine when I use it in my controller.

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Schedule
{
    private OffsetDateTime time;
    private String mode;
}

Using in my controller:

public ResponseEntity taskManagerTest() {
    Schedule bpTaskManagerRequest = new Schedule();

    return ResponseEntity.status(HttpStatus.CREATED).headers(null).body(bpTaskManagerRequest);
}

Example result when I am returning my object:

{
  "time": "2017-11-12T15:03:05.171Z",
  "mode": "eSetTime"
}

But if I use the same object to send it further using RestTemplate in my Spring service:

    HttpEntity<Schedule> httpEntity = new HttpEntity<>(bpTaskManagerRequest, headers);

    ResponseEntity<String> answer = restTemplate.exchange(bpTaskManagerURL, HttpMethod.POST, httpEntity,
            String.class);

It is serialized as:

{
    "time": 1510498985.171000000,
    "mode": "eSetTime"
}

My RestTemplate is defined as:

@Autowired
private RestTemplate restTemplate;

application.yml snippet:

spring:
    jackson:
        serialization:
            write-dates-as-timestamps: false

build.gradle snippet:

buildscript {
    ext {
        springBootVersion = '1.5.4.RELEASE'
        ext.kotlin_version = '1.1.51'
    }
}
compile('com.fasterxml.jackson.module:jackson-module-parameter-names')
compile('com.fasterxml.jackson.datatype:jackson-datatype-jdk8')
compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310')

Example project: https://github.com/deepres/OffsetDateTime-with-RestTemplate

Body:
Your application is creating its own RestTemplate bean and not applying any customisation to it. This means that it will be use the default message converters and default Jackson configuration, rather than anything that's configured by Spring Boot.

As described in the reference documentation, Spring Boot provides a RestTemplateBuilder that can be used to create a RestTemplate. It "will ensure that sensible HttpMessageConverters are applied to RestTemplate instances". You can update your example to use it by changing WebConfiguration to the following:

package com.example.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;

@Configuration
public class WebConfiguration {

    @Bean
    public RestTemplate getRestTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

}

With this change in place, the conversion is now consistent:

2017-11-17 12:35:02.892  INFO 28527 --- [nio-8080-exec-2] com.example.demo.ExampleController       : Rest template: {"label":"test from controller","time":"2017-11-17T12:35:02.821Z"}
2017-11-17 12:35:02.905  INFO 28527 --- [nio-8080-exec-1] com.example.demo.DemoService             : Object mapper:{"label":"test from controller","time":"2017-11-17T12:35:02.821Z"}


问:
Is there a way to print out a specific div of a webpage as pdf?
I want to be able to print out a specific div as a PDF and JPG. I used the following code while running phantomjs:

var bb = page.evaluate(function() {
  return document.getElementsByTagName("fieldset")[7].getBoundingClientRect();
});

page.clipRect = {
  top: bb.top,
  left: bb.left,
  width: bb.width,
  height: bb.height
};
```

This works fine for PNG but for PDF it just prints the whole page. Does anyone know why this is happening and how to solve it? If someone know of any other way to solve this, even something not involving phantomjs or some fronted solution, I'll be highly obliged if they share.

Edit I'm looking for a workaround to this problem, any frontend or backend solutions are acceptable.However some of the previous questions regarding this topic provide suggestions that involve html2canvas or jsPdf but those have problems with resolution so any other answers solutions will be appreciated.

答:
I needeed to send div to PDF, I use this code and work fine for me. (need JQuery).

 function testPdf(){

    //send the div to PDF
    html2canvas($("#DIV_ID_HERE"), { // DIV ID HERE
        onrendered: function(canvas) {
            var imgData = canvas.toDataURL('image/png');
            var doc = new jsPDF('landscape');
            doc.addImage(imgData, 'PDF', 10, 10);
            doc.save('sample-file.pdf'); //SAVE PDF FILE
        }
    });

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.debug.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>

<div id="DIV_ID_HERE">

 Test - This div to pdf
 <br><input type="button" value="print" onclick="testPdf();">
<div></code>```

Body:
I want to be able to print out a specific div as a PDF and JPG. I used the following code while running phantomjs:

var bb = page.evaluate(function() {
  return document.getElementsByTagName("fieldset")[7].getBoundingClientRect();
});

page.clipRect = {
  top: bb.top,
  left: bb.left,
  width: bb.width,
  height: bb.height
};

This works fine for PNG but for PDF it just prints the whole page. Does anyone know why this is happening and how to solve it? If someone know of any other way to solve this, even something not involving phantomjs or some fronted solution, I'll be highly obliged if they share.

Edit I'm looking for a workaround to this problem, any frontend or backend solutions are acceptable.However some of the previous questions regarding this topic provide suggestions that involve html2canvas or jsPdf but those have problems with resolution so any other answers solutions will be appreciated.

Body:
I needeed to send div to PDF, I use this code and work fine for me. (need JQuery).

 function testPdf(){

    //send the div to PDF
    html2canvas($("#DIV_ID_HERE"), { // DIV ID HERE
        onrendered: function(canvas) {
            var imgData = canvas.toDataURL('image/png');
            var doc = new jsPDF('landscape');
            doc.addImage(imgData, 'PDF', 10, 10);
            doc.save('sample-file.pdf'); //SAVE PDF FILE
        }
    });

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.debug.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>

<div id="DIV_ID_HERE">

 Test - This div to pdf
 <br><input type="button" value="print" onclick="testPdf();">
<div>


问:
How to push both value and key into PHP array
Take a look at this code:

```<code>$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
</code>```

I'm looking for something like this so that:

```<code>print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
</code>```

Is there a function to do this? (because array_push won't work this way)

答:
array_push($GET, $GET['one']=1);
```

It works for me.

Body:
Take a look at this code:

$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */

I'm looking for something like this so that:

print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */

Is there a function to do this? (because array_push won't work this way)

Body:
array_push($GET, $GET['one']=1);

It works for me.


问:
Function parameters as pointers and return value in C
In the function i need to pass in myFlg and somVar as input parameters. They are modified withing the function and then returned newLevel.

Do i pass in pointers for myFlg and somVar and how do i do that. The flg and counter need to be updated inside the function but they are not globals. So pass in two parameters/pointers and return a value, one return value and two modified values/pointers.

```<code>     in flags.h
#define FlagReg1set_u         0b01000001

typedef union
{
    struct
    {
        uint8_t Flg1 : 1;
        uint8_t Flg2 : 1;
        uint8_t Flg3 : 1;
        uint8_t Flg4 : 1;
        uint8_t Flg5 : 1;
        uint8_t Flg6 : 1;
        uint8_t my_Flg : 1;
        uint8_t foo : 1;
    } bits;
    uint8_t byte;
} FlagReg1_t = FlagReg1set_u;

in level.c
uint16_t level(uint8_t Flag, uint8_t SomeVariable, uint8_t SomeCount)
{

    static uint16_t newLevel = SomeVariable;
    static uint8_t count = SomeCount;
    static uint8_t somVar;

if (FlagReg1.bits.my_Flg == 1)
    {
    /* do something */
    newLevel = 0xFFFF;
    }
else
    {
      FlagReg1.bits.my_Flg = 0
    }

if (somVar == SomeVariable)
    {
    count = 0;
    }
    else
    {
    count++;
    }

return newLevel
}

in main .c
#include "flags.h"

main()
{
/* Variable Declaration */
uint16_t level(uint8_t Flag, uint8_t SomeVariable, uint8_t SomeCount);

    uint8_t count = 0;
    uint8_t ownlevel;
    uint16_t newLevel;

    level(FlagReg1_t my_Flg, ownlevel, count);

    if (newLevel == 0)
    {
    //do something
    }
    else
    {
    //do something
    }

}
</code>```

答:
Well excuses to the community I use answer space , this is more a comment but I need the tools to explain.
So , eumac , the usual purpose of a union is:

```<code>typedef union eumac_un_t
{
    struct eumac_str
    {
        uint8_t flag_4;
        uint8_t flag_3;
        uint8_t flag_2;
        uint8_t flag_1;
    };
int the_flag;
}eumac_un;
</code>```

This takes 4 bytes (a memory area) , stores the same data which can be retrieved in all the various ways.
Example if you store

```<code>eumac_un_t.eumac_str.flag_1 = 150  //(1001 0110)
eumac_un_t.eumac_str.flag_2 = 20  //(0001 0100)
</code>```

what you get for

```<code>eumac_un_t.the_flag == 5270 //its 0000 0000 - 0000 0000 - 0001 0100 - 1001 0110
</code>```

This is why we use a union.So in your case you won't need it.Is that clear??

Now in your case , usually you pass as pointers when you have an array.If flag is just an integer , then you can simply pass it as an integer.

So yes , exactly the function you mention is very nice

```<code>    uint16_t level(FlagReg1_t *ptrToFlagReg1, uint8_t *SomeVariable, uint8_t *SomeCount)
{
    ptrToFlagReg1->something = something;
    ptrToFlagReg1->something_else = something_else;
    return number_of_something;
}
</code>```

Integers don't really have to be passed as pointers if there's no need to.

```<code>uint8_t SomeVariable, uint8_t SomeCount
</code>```

Body:
In the function i need to pass in myFlg and somVar as input parameters. They are modified withing the function and then returned newLevel.

Do i pass in pointers for myFlg and somVar and how do i do that. The flg and counter need to be updated inside the function but they are not globals. So pass in two parameters/pointers and return a value, one return value and two modified values/pointers.

     in flags.h
#define FlagReg1set_u         0b01000001

typedef union
{
    struct
    {
        uint8_t Flg1 : 1;
        uint8_t Flg2 : 1;
        uint8_t Flg3 : 1;
        uint8_t Flg4 : 1;
        uint8_t Flg5 : 1;
        uint8_t Flg6 : 1;
        uint8_t my_Flg : 1;
        uint8_t foo : 1;
    } bits;
    uint8_t byte;
} FlagReg1_t = FlagReg1set_u;

in level.c
uint16_t level(uint8_t Flag, uint8_t SomeVariable, uint8_t SomeCount)
{

    static uint16_t newLevel = SomeVariable;
    static uint8_t count = SomeCount;
    static uint8_t somVar;

if (FlagReg1.bits.my_Flg == 1)
    {
    /* do something */
    newLevel = 0xFFFF;
    }
else
    {
      FlagReg1.bits.my_Flg = 0
    }

if (somVar == SomeVariable)
    {
    count = 0;
    }
    else
    {
    count++;
    }

return newLevel
}

in main .c
#include "flags.h"

main()
{
/* Variable Declaration */
uint16_t level(uint8_t Flag, uint8_t SomeVariable, uint8_t SomeCount);

    uint8_t count = 0;
    uint8_t ownlevel;
    uint16_t newLevel;

    level(FlagReg1_t my_Flg, ownlevel, count);

    if (newLevel == 0)
    {
    //do something
    }
    else
    {
    //do something
    }

}

Body:
Well excuses to the community I use answer space , this is more a comment but I need the tools to explain.
So , eumac , the usual purpose of a union is:

typedef union eumac_un_t
{
    struct eumac_str
    {
        uint8_t flag_4;
        uint8_t flag_3;
        uint8_t flag_2;
        uint8_t flag_1;
    };
int the_flag;
}eumac_un;

This takes 4 bytes (a memory area) , stores the same data which can be retrieved in all the various ways.
Example if you store

eumac_un_t.eumac_str.flag_1 = 150  //(1001 0110)
eumac_un_t.eumac_str.flag_2 = 20  //(0001 0100)

what you get for

eumac_un_t.the_flag == 5270 //its 0000 0000 - 0000 0000 - 0001 0100 - 1001 0110

This is why we use a union.So in your case you won't need it.Is that clear??

Now in your case , usually you pass as pointers when you have an array.If flag is just an integer , then you can simply pass it as an integer.

So yes , exactly the function you mention is very nice

    uint16_t level(FlagReg1_t *ptrToFlagReg1, uint8_t *SomeVariable, uint8_t *SomeCount)
{
    ptrToFlagReg1->something = something;
    ptrToFlagReg1->something_else = something_else;
    return number_of_something;
}

Integers don't really have to be passed as pointers if there's no need to.

uint8_t SomeVariable, uint8_t SomeCount


问:
Braintree partial settlement not working
Braintree Partial Settlement not working for this code .If I write this code the page set blank with no error or no message.

```<code>Braintree\Transaction::submitForPartialSettlement('transaction_id', '10.00');
</code>```

please give answer if anyone have idea.

答:
Multiple partial settlements are only available for PayPal transactions.</p>

```<code>$result = Braintree_Transaction::submitForPartialSettlement('theParentAuthTransactionId', '10.00');

    if ($result->success) {
        $settledTransaction = $result->transaction;
    } else {
        print_r($result->errors);
    }
</code>```

Body:
Braintree Partial Settlement not working for this code .If I write this code the page set blank with no error or no message.

Braintree\Transaction::submitForPartialSettlement('transaction_id', '10.00');

please give answer if anyone have idea.

Body:
Multiple partial settlements are only available for PayPal transactions.

$result = Braintree_Transaction::submitForPartialSettlement('theParentAuthTransactionId', '10.00');

    if ($result->success) {
        $settledTransaction = $result->transaction;
    } else {
        print_r($result->errors);
    }


问:
How can i Iterate through data returned in Ajax success?
How can I iterate to get id value? This is my array:

```<code>[{"email_id":"gayatri.dsf@detedu.org","Id":"216"}]
</code>```

tried

```<code><?php
    foreach($faculty as $value)
    {
       echo $value['Id'];
    }
?>
</code>```

Gives an error

Use of undefined constant Id - assumed Id

答:
This is a json which is basically a string, to be more precise the given json contains a list (currently 1 element):

```<code>[{"email_id":"gayatri.dsf@detedu.org","Id":"216"}]
</code>```

You need to convert it to an array first:

```<code>$jsonValues = json_decode($json, true); //here you will have an array of users (1 now)
foreach($jsonValues as $faculty) //for each user do something
{
    echo $faculty['Id'];
}
</code>```

Body:
How can I iterate to get id value? This is my array:

[{"email_id":"gayatri.dsf@detedu.org","Id":"216"}]

tried

<?php
    foreach($faculty as $value)
    {
       echo $value['Id'];
    }
?>

Gives an error

Use of undefined constant Id - assumed Id

Body:
This is a json which is basically a string, to be more precise the given json contains a list (currently 1 element):

[{"email_id":"gayatri.dsf@detedu.org","Id":"216"}]

You need to convert it to an array first:

$jsonValues = json_decode($json, true); //here you will have an array of users (1 now)
foreach($jsonValues as $faculty) //for each user do something
{
    echo $faculty['Id'];
}


问:
How to transfer databases and site contents
I own a website with 20 GB data on it Now I decided to change the Hosting compnay .
I'm Moving to Russian VPS so is there a way to transfer the contents of my website to the Russian VPS without uploading them again .

Is there a service that does this.
I heard that there is a way to do this using shell access (BUT what is shell access and how it works)
thanx in advance guys

答:
You can log in to one of your old host using an SSH connection, then connect from there to your new host, again using an SSH connection, and then upload all files from your first server to the second. For databases, do a data dump on your first server, and through the SSH connection, run the data dump against a database on your new server.

Depending on the hosts, how you connect via SSH will differ, but there should be instruction available from the providers. If you can't find the directions, just e-mail the provider's support and ask.

OwnerDisplayName: umtoz

OwnerDisplayName: Elie


问:
Hide/handle servlet exception stack trace output
From this post I have thought of another question I cannot seem to find the answer to on the interweb.

I have a servlet filter which detects session timeouts and redirects to an error page.  Due to my fledgling java I've used try catch blocks to catch exceptions and handle them gracefully, but in a session timeout situation, the context is invalid so I don't think I've got any code I can do that with which will stop the 'viewId could not be restored' stace trace appearing in my log even though I have a filter handling it.

How can I stop the exception trace from appearing in my log?  It will be monitored autoamtically in live and it will be a false positive call out to the support team for this sort of error.

Any help appreciated.

EDIT

To be more clear, my code clip is currently

```<code>public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } catch (ServletException e) {
        logger.error("Caught Servlet Exception");
        Throwable rootCause = e.getRootCause();
        logger.error("Root cause is " + rootCause.toString());

        if (rootCause instanceof RuntimeException) { // This is true for any FacesException.
            logger.error("Rethrowing exception as RuntimeException" + rootCause.toString());
            throw (RuntimeException) rootCause; // Throw wrapped RuntimeException instead of ServletException.
        } else {
            throw e;
        }
    }
}
</code>```

The log says:

```<code>    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Exception in the filter chain
    javax.servlet.ServletException: viewId:/index.jsf - View /index.jsf could not be restored.
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:270)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
        at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
<snip>
        at java.lang.Thread.run(Unknown Source)
    Caused by: javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
<snip>
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
        ... 21 more
    19-Jan-2011 10:40:57 org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet Faces Servlet threw exception
    javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
        at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:185)
<snip>
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Unknown Source)
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Caught Servlet Exception
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Root cause is javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Rethrowing exception as RuntimeExceptionjavax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
</code>```

As you can see from the code, I've caught the servlet exception in the filter, but the stack is still appearing in the log.

NEXT EDIT
The complete list of filters in my web.xml is as follows:

```<code><filter>
    <filter-name>Error</filter-name>
    <filter-class>prismClient.ErrorFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Error</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <display-name>RichFaces Filter</display-name>
    <filter-name>richfaces</filter-name>
    <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
    <filter-name>richfaces</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>
</code>```

答:
Possibly because you rethrow the exception, whatever is logging it is still getting it.  Even though you're blocking the ServletException out and rethrowing the RunTimeException (which ViewExpiredException is), something higher in the filter chain may be rewrapping it.

Do any of the logs you write in this method also show up in the log before the stacktrace?

Body:
From this post I have thought of another question I cannot seem to find the answer to on the interweb.

I have a servlet filter which detects session timeouts and redirects to an error page.  Due to my fledgling java I've used try catch blocks to catch exceptions and handle them gracefully, but in a session timeout situation, the context is invalid so I don't think I've got any code I can do that with which will stop the 'viewId could not be restored' stace trace appearing in my log even though I have a filter handling it.

How can I stop the exception trace from appearing in my log?  It will be monitored autoamtically in live and it will be a false positive call out to the support team for this sort of error.

Any help appreciated.

EDIT

To be more clear, my code clip is currently

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } catch (ServletException e) {
        logger.error("Caught Servlet Exception");
        Throwable rootCause = e.getRootCause();
        logger.error("Root cause is " + rootCause.toString());

        if (rootCause instanceof RuntimeException) { // This is true for any FacesException.
            logger.error("Rethrowing exception as RuntimeException" + rootCause.toString());
            throw (RuntimeException) rootCause; // Throw wrapped RuntimeException instead of ServletException.
        } else {
            throw e;
        }
    }
}

The log says:

    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Exception in the filter chain
    javax.servlet.ServletException: viewId:/index.jsf - View /index.jsf could not be restored.
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:270)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
        at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
<snip>
        at java.lang.Thread.run(Unknown Source)
    Caused by: javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
<snip>
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
        ... 21 more
    19-Jan-2011 10:40:57 org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet Faces Servlet threw exception
    javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
        at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:185)
<snip>
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Unknown Source)
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Caught Servlet Exception
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Root cause is javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Rethrowing exception as RuntimeExceptionjavax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.

As you can see from the code, I've caught the servlet exception in the filter, but the stack is still appearing in the log.

NEXT EDIT
The complete list of filters in my web.xml is as follows:

<filter>
    <filter-name>Error</filter-name>
    <filter-class>prismClient.ErrorFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Error</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <display-name>RichFaces Filter</display-name>
    <filter-name>richfaces</filter-name>
    <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
    <filter-name>richfaces</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>


问:
F# Cannot enumerate sequence generated by yield when using GetEnumerator
The following example is based on a snippet that produces functions that allow enumerating sequence values one by one.

Here printAreEqual () gives true, print2 () gives 12345678910, but print1 () gives 0000000000.

Why cannot the function returned by enumerate return the values of the sequence generated using yield?

```<code>open System.Linq

let enumerate (xs: seq<_>)  =
    use en = xs.GetEnumerator()
    fun () ->
        en.MoveNext() |> ignore
        en.Current

let s1 = seq { for i in 1 .. 10 do yield i }
let s2 = seq { 1 .. 10 }

let f1 = s1 |> enumerate
let f2 = s2 |> enumerate

let printAreEqual () = Enumerable.SequenceEqual (s1, s2) |> printf "%b" // true
let print1 () = for i in 1 .. 10 do f1() |> printf "%i" // 0000000000
let print2 () = for i in 1 .. 10 do f2() |> printf "%i" // 12345678910
</code>```

答:
The use en = ... in the enumerate function is effectively doing this:

```<code>let enumerate (xs: seq<_>) =
    let en = xs.GetEnumerator()
    let f =
        fun () ->
            en.MoveNext() |> ignore
            en.Current
    en.Dispose()
    f
</code>```

You're always disposing of the enumerator before you start using it, so the behaviour is probably undefined in this situation and it doesn't matter why you get different results for two sequences with different implementations.

Fine-grained control of sequence enumeration is always tricky and it's hard to make helper functions for because of the mutable state.

Body:
The following example is based on a snippet that produces functions that allow enumerating sequence values one by one.

Here printAreEqual () gives true, print2 () gives 12345678910, but print1 () gives 0000000000.

Why cannot the function returned by enumerate return the values of the sequence generated using yield?

open System.Linq

let enumerate (xs: seq<_>)  =
    use en = xs.GetEnumerator()
    fun () ->
        en.MoveNext() |> ignore
        en.Current

let s1 = seq { for i in 1 .. 10 do yield i }
let s2 = seq { 1 .. 10 }

let f1 = s1 |> enumerate
let f2 = s2 |> enumerate

let printAreEqual () = Enumerable.SequenceEqual (s1, s2) |> printf "%b" // true
let print1 () = for i in 1 .. 10 do f1() |> printf "%i" // 0000000000
let print2 () = for i in 1 .. 10 do f2() |> printf "%i" // 12345678910

Body:
The use en = ... in the enumerate function is effectively doing this:

let enumerate (xs: seq<_>) =
    let en = xs.GetEnumerator()
    let f =
        fun () ->
            en.MoveNext() |> ignore
            en.Current
    en.Dispose()
    f

You're always disposing of the enumerator before you start using it, so the behaviour is probably undefined in this situation and it doesn't matter why you get different results for two sequences with different implementations.

Fine-grained control of sequence enumeration is always tricky and it's hard to make helper functions for because of the mutable state.


问:
Mono Pkg-Config.exe Keeps Crashing?
I'm new to Mono - thought I'd give cross platform a try - my main IDE is Visual Studio and so the process of building applications through the command prompt is a bit foreign to me.

I was following the Mono Basics tutorial, and have gotten to the point where it says Winforms Hello World. I copied the code provided and saved it to a .cs file (on the Desktop).

I then opened up a command prompt and pointed it towards the Desktop directory. I ran the command:

```<code>mcs hello.cs -pkg:dotnet
</code>```

And the result was:

The console told me that it was a CS8027 error but nothing else.

I have 3 environment variables that I added, with no fix:

PATH -> path to mono\bin

PATH -> path to mono\lib\pkgconfig

PKG_CONFIG_PATH -> path to mono\lib\pkgconfig

This happens whenever I try to use pkg-config.exe (tried to use pkg-config.exe --list-all but the same problem arose).

I've checked other answers/questions about the CS8027 error but the solutions did not help - it still crashes every time!

答:
I had this problem, could help some.

```<code>D:\Code\Mono>mcs hello.cs -pkg:dotnet
error CS8027: Error running pkg-config. Check the above output.
</code>```

I needed to download the following DLL:s from https://www.dll-files.com/

libiconv-2.dll

libgcc_s_sjlj-1.dll

libintl-8.dll

libglib-2.0-0.dll

Put them in C:\Program Files\Mono\bin

All DLLs should be 32 bits even if Mono was 64 bits.

Title: Mono Pkg-Config.exe Keeps Crashing?

Body:
I'm new to Mono - thought I'd give cross platform a try - my main IDE is Visual Studio and so the process of building applications through the command prompt is a bit foreign to me.

I was following the Mono Basics tutorial, and have gotten to the point where it says Winforms Hello World. I copied the code provided and saved it to a .cs file (on the Desktop).

I then opened up a command prompt and pointed it towards the Desktop directory. I ran the command:

mcs hello.cs -pkg:dotnet

And the result was:

The console told me that it was a CS8027 error but nothing else.

I have 3 environment variables that I added, with no fix:

PATH -> path to mono\bin

PATH -> path to mono\lib\pkgconfig

PKG_CONFIG_PATH -> path to mono\lib\pkgconfig

This happens whenever I try to use pkg-config.exe (tried to use pkg-config.exe --list-all but the same problem arose).

I've checked other answers/questions about the CS8027 error but the solutions did not help - it still crashes every time!

Body:
I had this problem, could help some.

D:\Code\Mono>mcs hello.cs -pkg:dotnet
error CS8027: Error running pkg-config. Check the above output.

I needed to download the following DLL:s from https://www.dll-files.com/

libiconv-2.dll

libgcc_s_sjlj-1.dll

libintl-8.dll

libglib-2.0-0.dll

Put them in C:\Program Files\Mono\bin

All DLLs should be 32 bits even if Mono was 64 bits.