问:
Clear an interval when the last element is update
I'm trying to stop an interval when my last element is update.

I do not know how to do. Can you get me started on tracks?

At the moment I clear my interval when I leave the page.

```<code>    this.subscriptions.push(this.requestId.subscribe(id => {
        this.store.dispatch(new requestActions.LoadRequest(id));
        this.interval = setInterval(() => {
            this.store.dispatch(new requestActions.LoadRequest(id));
        }, 1700);
    }));
</code>```

My effect :

```<code>@Effect()
loadRequest$: Observable<Action> = this.actions$
    .ofType<requestActions.LoadRequest>(requestActions.LOAD_REQUEST)
    .switchMap(action => {
        return this.apiService
            .loadRequest(action.payload)
            .map((task: RequestTask[]) => new requestActions.LoadRequestSuccessAction(task))
            .catch(error => of(new requestActions.LoadRequestFailureAction(error)));
    });
</code>```

my reducer :

```<code>    case request.LOAD_REQUEST_SUCCESS:
        console.log("Payload : ", action.payload);
        return {
            ...adapter.addAll(action.payload, state),
            loaded: true,
            selectedIndex: null
        } as State;
</code>```

答:
I managed to solve my problem by doing this:

```<code>export interface State extends EntityState<Event> {
request: Request }
</code>```

I create a function

```<code>function getStatusOfEvents(payload : any){
const object = payload as Event[]
const events = object.map(obj => obj.status);

if (events.includes("PENDING")){
    return true;
} else {
    return false;
} }
</code>```

I place the value in the store :

```<code>export function reducer(state: State = initialState, action: request.Actions): State {
switch (action.type) {
    case request.LOAD_EVENTS_SUCCESS:
        console.log("Payload events : ", action.payload);
        const status = getStatusOfEvents(action.payload)
        return {
            ...adapter.addAll(action.payload, state),
            refresh: status,
            loaded: true,
        } as State;
    case request.LOAD_EVENTS:
    case request.LOAD_EVENTS_FAILURE:
    default:
        return state;
}
</code>```

}

And finally I "clear" my interval when the return value is false

```<code>refresh: boolean;

this.subscriptions.push(this.requestId.subscribe(id => {
        this.store.dispatch(new requestActions.LoadEvents(id));
        this.interval = setInterval(() => {
            this.store.dispatch(new requestActions.LoadEvents(id));
            this.store.select(fromRoot.getRefreshEntitiesState).subscribe(data => this.refresh = data)
            console.log("Refresh :", this.refresh)
            if (this.refresh != undefined && this.refresh === false) {
                clearInterval(this.interval);
            }
        }, 1700);
    }))
</code>```

Body:
I'm trying to stop an interval when my last element is update.

I do not know how to do. Can you get me started on tracks?

At the moment I clear my interval when I leave the page.

    this.subscriptions.push(this.requestId.subscribe(id => {
        this.store.dispatch(new requestActions.LoadRequest(id));
        this.interval = setInterval(() => {
            this.store.dispatch(new requestActions.LoadRequest(id));
        }, 1700);
    }));

My effect :

@Effect()
loadRequest$: Observable<Action> = this.actions$
    .ofType<requestActions.LoadRequest>(requestActions.LOAD_REQUEST)
    .switchMap(action => {
        return this.apiService
            .loadRequest(action.payload)
            .map((task: RequestTask[]) => new requestActions.LoadRequestSuccessAction(task))
            .catch(error => of(new requestActions.LoadRequestFailureAction(error)));
    });

my reducer :

    case request.LOAD_REQUEST_SUCCESS:
        console.log("Payload : ", action.payload);
        return {
            ...adapter.addAll(action.payload, state),
            loaded: true,
            selectedIndex: null
        } as State;

Body:
I managed to solve my problem by doing this:

export interface State extends EntityState<Event> {
request: Request }

I create a function

function getStatusOfEvents(payload : any){
const object = payload as Event[]
const events = object.map(obj => obj.status);

if (events.includes("PENDING")){
    return true;
} else {
    return false;
} }

I place the value in the store :

export function reducer(state: State = initialState, action: request.Actions): State {
switch (action.type) {
    case request.LOAD_EVENTS_SUCCESS:
        console.log("Payload events : ", action.payload);
        const status = getStatusOfEvents(action.payload)
        return {
            ...adapter.addAll(action.payload, state),
            refresh: status,
            loaded: true,
        } as State;
    case request.LOAD_EVENTS:
    case request.LOAD_EVENTS_FAILURE:
    default:
        return state;
}

}

And finally I "clear" my interval when the return value is false

refresh: boolean;

this.subscriptions.push(this.requestId.subscribe(id => {
        this.store.dispatch(new requestActions.LoadEvents(id));
        this.interval = setInterval(() => {
            this.store.dispatch(new requestActions.LoadEvents(id));
            this.store.select(fromRoot.getRefreshEntitiesState).subscribe(data => this.refresh = data)
            console.log("Refresh :", this.refresh)
            if (this.refresh != undefined && this.refresh === false) {
                clearInterval(this.interval);
            }
        }, 1700);
    }))


来源: stackexchange

问:
Resize table inside overflowing divs without JS
Is it possible to resize columns in scrollable table when width of all columns has more pixels than div which contains table. The problem is I have something like 20 columns and I need to have my table scrollable with possibility of resizing columns. I successfully did it with JS mousemove, mouseup and mousedown events but I'm trying to do it with CSS it will cost user less resources. Example below:</p>

```<code><div style="overflow-x:scroll;overflow-y:scroll;max-height:300px;max-width:500px;background-color:gray;">
  <table>
    <thead>
      <tr>
          <th style="resize:horizontal;overflow: auto;">TESTTESTESTEST</th>
          <th style="resize:horizontal;overflow: auto;">TESTTESTESTEST</th>
          <th style="resize:horizontal;overflow: auto;">TESTTESTESTEST</th>
          <th style="resize:horizontal;overflow: auto;">TESTTESTESTEST</th>
          <th style="resize:horizontal;overflow: auto;">TESTTESTESTEST</th>
          <th style="resize:horizontal;overflow: auto;">TESTTESTESTEST</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>TESTTESTESTESTESTSTETSET</td>
        <td>TESTTESTESTESTESTSTETSET</td>
        <td>TESTTESTESTESTESTSTETSET</td>
        <td>TESTTESTESTESTESTSTETSET</td>
        <td>TESTTESTESTESTESTSTETSET</td>
        <td>TESTTESTESTESTESTSTETSET</td>
      </tr>
    </tbody>
  </table>
</div>
</code>```

答:
Check this code, if this is what you are looking for:

<!DOCTYPE html>

Table which can scroll and column will automatically resize

      First Name
      Last Name
      Points
      Points
      Points
      Points
      Points
      Points
      Points
      Points
      Points
      Points

      hello
      bye
      50
      50
      50
      50
      50
      50
      50
      50
      50
      50

      Abc
      xyz
      94
      94
      94
      94
      94
      94
      94
      94
      94
      94

      Arun
      Kumar
      67
      67
      67
      67
      67
      67
      67
      67
      67
      67

```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to resize columns in scrollable table when width of all columns has more pixels than div which contains table. The problem is I have something like 20 columns and I need to have my table scrollable with possibility of resizing columns. I successfully did it with JS mousemove, mouseup and mousedown events but I'm trying to do it with CSS it will cost user less resources. Example below:

          TESTTESTESTEST
          TESTTESTESTEST
          TESTTESTESTEST
          TESTTESTESTEST
          TESTTESTESTEST
          TESTTESTESTEST

        TESTTESTESTESTESTSTETSET
        TESTTESTESTESTESTSTETSET
        TESTTESTESTESTESTSTETSET
        TESTTESTESTESTESTSTETSET
        TESTTESTESTESTESTSTETSET
        TESTTESTESTESTESTSTETSET

Body:
Check this code, if this is what you are looking for:

<!DOCTYPE html>
<html>
<head>
<style>
table {
    border-collapse: collapse;
    border-spacing: 0;
    width: 100%;
    border: 1px solid #ddd;
}

th, td {
    text-align: left;
    padding: 8px;
}

tr:nth-child(even){background-color: #f2f2f2}
</style>
</head>
<body>

<h2>Table which can scroll and column will automatically resize</h2>
<div style="overflow-x:auto;">
  <table>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Points</th>
      <th>Points</th>
      <th>Points</th>
      <th>Points</th>
      <th>Points</th>
      <th>Points</th>
      <th>Points</th>
      <th>Points</th>
      <th>Points</th>
      <th>Points</th>
    </tr>
    <tr>
      <td>hello</td>
      <td>bye</td>
      <td>50</td>
      <td>50</td>
      <td>50</td>
      <td>50</td>
      <td>50</td>
      <td>50</td>
      <td>50</td>
      <td>50</td>
      <td>50</td>
      <td>50</td>
    </tr>
    <tr>
      <td>Abc</td>
      <td>xyz</td>
      <td>94</td>
      <td>94</td>
      <td>94</td>
      <td>94</td>
      <td>94</td>
      <td>94</td>
      <td>94</td>
      <td>94</td>
      <td>94</td>
      <td>94</td>
    </tr>
    <tr>
      <td>Arun</td>
      <td>Kumar</td>
      <td>67</td>
      <td>67</td>
      <td>67</td>
      <td>67</td>
      <td>67</td>
      <td>67</td>
      <td>67</td>
      <td>67</td>
      <td>67</td>
      <td>67</td>
    </tr>
  </table>
</div>

</body>
</html>


问:
Any plugin doesn't works / wordpress
Hi everyone,

first sorry for my english I´m not a native speaker.

I work for my friend on web based on wordpress. It´s simple small web with four sub-pages. He had web there before, but he don´t carre about him. He had there some malware so I decided delete all ( including databases ) and do new instalation. I instaled theme Alhena-lite - its free theme.

I added my own css, and on contact page I added google javascipt map api. Then I downloaded plugin ( contact form 7 ), activated and then if I´m wanted customize site I see only blank page - without error alert.  All others functions work correctly except this. And plugin doesn´t work correct too.

OK, I said, probably theme and plugin are incompatible, so I deleted contact form and I download and activated NINJA FORMS - situation was same as was before.

Ok, I tried other plugin and situation was same. If a deactivate this plugins everything was correct ( I  had active only one plugin in same time ).

I tried reinstal the newest version WP, but problem persisted. I tried change permissions - nothing are happen. I tried also activated basic WP theme twenty seventeen and issue persist. The problem with the free space on hosting is certainly not.

I found in the console this:

Could not load the source for http://www.vlasak-kominy.cz/wp-admin/customize.php?url=http%3A%2F%2Fwww.vlasak-kominy.cz%2F.
[Exception… “Component returned failure code: 0x80470002 (NS_BASE_STREAM_CLOSED) [nsIInputStream.available]” nsresult: “0x80470002 (NS_BASE_STREAM_CLOSED)” location: “JS frame :: resource://gre/modules/commonjs/toolkit/loader.js -> resource://devtools/shared/DevToolsUtils.js :: onResponse :: line 464” data: no]
Stack: onResponse@resource://gre/modules/commonjs/toolkit/loader.js -> resource://devtools/shared/DevToolsUtils.js:464:23
onStopRequest@resource://gre/modules/NetUtil.jsm:131:17
Line: 464, column: 0

But I don´t know how solve it and I tried find answer everywhere.

I also found that my hosting use PHP 5.3 ( I sent a request to upgrade on 5.6version because 7 is not available there ). Can be reason issue this ? I cannot activate any plugin.

I believe that you understand my english and thanks in advance.

Richard

答: Thank you for you answer - yesterday evening my hosting upgraded me php version from 5.3 to 5.6 and seems to everything work correct.  WP recommend at least 5.6 version so probably it was cause my problems.</p>

Title: Any plugin doesn't works / wordpress


问:
Window-select multiple artists and drag them on canvas

Aim

I would like to simultaneously:

1) Select multiple artists on a matplotlib canvas by window-select.

By that I mean that if I hold down the mouse button, drag the mouse,
and release, all artists in the rectangle defined by the x,y locations
of the button press and the button release are picked.

2) Drag multiple selected artists by then pressing the mouse down over
one of the selected artists and moving the mouse, and releasing.

This is exactly the same behaviour as one would expect in a normal file browser.

Previous attempts and remaining problems

To that end, I have started to write two classes, WindowSelect and
Draggable, which are shown below.

WindowSelect implements the logic for (1) apart from the fact that I
don't know how to manually trigger the picker function, as it is
referred to in the matplotlib documentation.
Instead I call a place holder function func.

Draggable implements the logic for (2) apart from the fact that a
single artist is picked at a time (shamelessly appropriated from
another indicated SO answer).  The matplotlib
documentation
indicates that the picking of multiple artists simultaneously should
be possible (last example on the web page). However, if I, for
example, set the tolerance for the picker very high, only a single
artist appears to get selected / can then be dragged around on the
canvas, so I am unsure how the code needs to change to accommodate
multiple artists.

Code

```<code>import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import matplotlib.patches as patches

class WindowSelect(object):

    def __init__(self, artists):
        self.artists = artists
        self.canvases = set(artist.figure.canvas for artist in self.artists)

        for canvas in self.canvases:
            canvas.mpl_connect('button_press_event', self.on_press)
            canvas.mpl_connect('button_release_event', self.on_release)

        self.currently_dragging = False

    def on_press(self, event):
        if not self.currently_dragging:
            self.x0 = event.xdata
            self.y0 = event.ydata
            self.currently_dragging = True

    def on_release(self, event):
        if self.currently_dragging:
            self.x1 = event.xdata
            self.y1 = event.ydata

            for artist in self.artists:
                if self.is_inside_rect(*artist.center):
                    self.func(artist)

            for canvas in self.canvases:
                canvas.draw()

            self.currently_dragging = False

    def is_inside_rect(self, x, y):
        xlim = np.sort([self.x0, self.x1])
        ylim = np.sort([self.y0, self.y1])
        if (xlim[0]<=x) and (x<xlim[1]) and (ylim[0]<=y) and (y<ylim[1]):
            return True
        else:
            return False

    def func(self, artist):
        artist.set_color('k') # <- just an example operation; would like to pick artist instead

class Draggable(object):
    """
    https://stackoverflow.com/questions/21654008/matplotlib-drag-overlapping-points-interactively
    """
    def __init__(self, artists, tolerance=5):
        for artist in artists:
            artist.set_picker(tolerance)
        self.artists = artists
        self.currently_dragging = False
        self.current_artist = None
        self.offset = (0, 0)

        for canvas in set(artist.figure.canvas for artist in self.artists):
            canvas.mpl_connect('button_press_event', self.on_press)
            canvas.mpl_connect('button_release_event', self.on_release)
            canvas.mpl_connect('pick_event', self.on_pick)
            canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):
        self.currently_dragging = True

    def on_release(self, event):
        self.currently_dragging = False
        self.current_artist = None

    def on_pick(self, event):
        if self.current_artist is None:
            self.current_artist = event.artist
            x0, y0 = event.artist.center
            x1, y1 = event.mouseevent.xdata, event.mouseevent.ydata
            self.offset = (x0 - x1), (y0 - y1)

    def on_motion(self, event):
        if not self.currently_dragging:
            return
        if self.current_artist is None:
            return
        dx, dy = self.offset
        self.current_artist.center = event.xdata + dx, event.ydata + dy
        self.current_artist.figure.canvas.draw()

def demo(TestClass):

    fig, ax = plt.subplots(1,1)
    xlim = [-5, 5]
    ylim = [-5, 5]
    ax.set(xlim=xlim, ylim=ylim)

    circles = [patches.Circle((3.0, 3.0), 0.5, fc='r', alpha=1.0),
               patches.Circle((0.0, 0.0), 0.5, fc='b', alpha=1.0),
               patches.Circle((0.0, 3.0), 0.5, fc='g', alpha=1.0)]

    for circle in circles:
        ax.add_patch(circle)

    return TestClass(circles)

if __name__ == '__main__':

    out1 = demo(Draggable)
    out2 = demo(WindowSelect)
</code>```

答:
The only modification your second class needs is to track and move multiple artists at once.  Modifying the following functions will allow for this.

```<code>def on_pick(self, event):
    if self.current_artist is None:
        self.current_artist = event.artist
        ecoord = array([event.mouseevent.xdata, event.mouseevent.ydata])
        self.offsets = [a.center for a in self.artists] - ecoord

def on_motion(self, event):
    if not self.currently_dragging:
        return
    if self.current_artist is None:
        return

    center = event.xdata, event.ydata
    for artist, delta in zip(self.artists, self.offsets):
        artist.center = center + delta
    self.artists[0].figure.canvas.draw()
</code>```

Body:
Aim

I would like to simultaneously:

1) Select multiple artists on a matplotlib canvas by window-select.

By that I mean that if I hold down the mouse button, drag the mouse,
and release, all artists in the rectangle defined by the x,y locations
of the button press and the button release are picked.

2) Drag multiple selected artists by then pressing the mouse down over
one of the selected artists and moving the mouse, and releasing.

This is exactly the same behaviour as one would expect in a normal file browser.

Previous attempts and remaining problems

To that end, I have started to write two classes, WindowSelect and
Draggable, which are shown below.

WindowSelect implements the logic for (1) apart from the fact that I
don't know how to manually trigger the picker function, as it is
referred to in the matplotlib documentation.
Instead I call a place holder function func.

Draggable implements the logic for (2) apart from the fact that a
single artist is picked at a time (shamelessly appropriated from
another indicated SO answer).  The matplotlib
documentation
indicates that the picking of multiple artists simultaneously should
be possible (last example on the web page). However, if I, for
example, set the tolerance for the picker very high, only a single
artist appears to get selected / can then be dragged around on the
canvas, so I am unsure how the code needs to change to accommodate
multiple artists.

Code

import numpy as np
import matplotlib.pyplot as plt; plt.ion()
import matplotlib.patches as patches

class WindowSelect(object):

    def __init__(self, artists):
        self.artists = artists
        self.canvases = set(artist.figure.canvas for artist in self.artists)

        for canvas in self.canvases:
            canvas.mpl_connect('button_press_event', self.on_press)
            canvas.mpl_connect('button_release_event', self.on_release)

        self.currently_dragging = False

    def on_press(self, event):
        if not self.currently_dragging:
            self.x0 = event.xdata
            self.y0 = event.ydata
            self.currently_dragging = True

    def on_release(self, event):
        if self.currently_dragging:
            self.x1 = event.xdata
            self.y1 = event.ydata

            for artist in self.artists:
                if self.is_inside_rect(*artist.center):
                    self.func(artist)

            for canvas in self.canvases:
                canvas.draw()

            self.currently_dragging = False

    def is_inside_rect(self, x, y):
        xlim = np.sort([self.x0, self.x1])
        ylim = np.sort([self.y0, self.y1])
        if (xlim[0]<=x) and (x<xlim[1]) and (ylim[0]<=y) and (y<ylim[1]):
            return True
        else:
            return False

    def func(self, artist):
        artist.set_color('k') # <- just an example operation; would like to pick artist instead

class Draggable(object):
    """
    https://stackoverflow.com/questions/21654008/matplotlib-drag-overlapping-points-interactively
    """
    def __init__(self, artists, tolerance=5):
        for artist in artists:
            artist.set_picker(tolerance)
        self.artists = artists
        self.currently_dragging = False
        self.current_artist = None
        self.offset = (0, 0)

        for canvas in set(artist.figure.canvas for artist in self.artists):
            canvas.mpl_connect('button_press_event', self.on_press)
            canvas.mpl_connect('button_release_event', self.on_release)
            canvas.mpl_connect('pick_event', self.on_pick)
            canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):
        self.currently_dragging = True

    def on_release(self, event):
        self.currently_dragging = False
        self.current_artist = None

    def on_pick(self, event):
        if self.current_artist is None:
            self.current_artist = event.artist
            x0, y0 = event.artist.center
            x1, y1 = event.mouseevent.xdata, event.mouseevent.ydata
            self.offset = (x0 - x1), (y0 - y1)

    def on_motion(self, event):
        if not self.currently_dragging:
            return
        if self.current_artist is None:
            return
        dx, dy = self.offset
        self.current_artist.center = event.xdata + dx, event.ydata + dy
        self.current_artist.figure.canvas.draw()

def demo(TestClass):

    fig, ax = plt.subplots(1,1)
    xlim = [-5, 5]
    ylim = [-5, 5]
    ax.set(xlim=xlim, ylim=ylim)

    circles = [patches.Circle((3.0, 3.0), 0.5, fc='r', alpha=1.0),
               patches.Circle((0.0, 0.0), 0.5, fc='b', alpha=1.0),
               patches.Circle((0.0, 3.0), 0.5, fc='g', alpha=1.0)]

    for circle in circles:
        ax.add_patch(circle)

    return TestClass(circles)

if __name__ == '__main__':

    out1 = demo(Draggable)
    out2 = demo(WindowSelect)

Body:
The only modification your second class needs is to track and move multiple artists at once.  Modifying the following functions will allow for this.

def on_pick(self, event):
    if self.current_artist is None:
        self.current_artist = event.artist
        ecoord = array([event.mouseevent.xdata, event.mouseevent.ydata])
        self.offsets = [a.center for a in self.artists] - ecoord

def on_motion(self, event):
    if not self.currently_dragging:
        return
    if self.current_artist is None:
        return

    center = event.xdata, event.ydata
    for artist, delta in zip(self.artists, self.offsets):
        artist.center = center + delta
    self.artists[0].figure.canvas.draw()


问:
GMT+2, TimeZone getOffset return 0
On Android (4.3) device, I set locate on TimeZone GMT+2

So my local time is 15.11.2017 15:12

So as result the UTC is 15.11.2017 13:12

minus (2 hours). OK.

I want to get timezone offset.

Here code:

```<code>private static TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
private static Calendar calUTC = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    public static int getTimeZoneRawOffset() {
        int offsetFromUtcMills = timeZoneUTC.getOffset(new Date().getTime());
        return offsetFromUtcMills;
    }

    public static int getTimeZoneOffset() {
        return calUTC.getTimeZone().getOffset(System.currentTimeMillis());
    }
</code>```

But both methods always return 0.

Why?

答:
I'm personally using

```<code>TimeZone.getDefault().getRawOffset();
</code>```

To get the the offset for my default timezone.

Example:

```<code>ticket.getPurchaseDate().setTime(ticket.getPurchaseDate().getTime() + TimeZone.getDefault().getRawOffset());
</code>```

Title: GMT+2, TimeZone getOffset return 0

Body:
On Android (4.3) device, I set locate on TimeZone GMT+2

So my local time is 15.11.2017 15:12

So as result the UTC is 15.11.2017 13:12

minus (2 hours). OK.

I want to get timezone offset.

Here code:

private static TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
private static Calendar calUTC = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    public static int getTimeZoneRawOffset() {
        int offsetFromUtcMills = timeZoneUTC.getOffset(new Date().getTime());
        return offsetFromUtcMills;
    }

    public static int getTimeZoneOffset() {
        return calUTC.getTimeZone().getOffset(System.currentTimeMillis());
    }

But both methods always return 0.

Why?

Body:
I'm personally using

TimeZone.getDefault().getRawOffset();

To get the the offset for my default timezone.

Example:

ticket.getPurchaseDate().setTime(ticket.getPurchaseDate().getTime() + TimeZone.getDefault().getRawOffset());


问:
Invalid nib registered for identifier ((null)) - nib must contain exactly one top level
I'm using a custom UITableViewCell. When I try to run my code, I got this exception stack and I can't understand the source of the problem:

```<code>terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid nib registered for identifier ((null)) - nib must contain exactly one top level object which must be a UITableViewCell instance'
</code>```

Please note I am not using Storyboard.

EDIT:

This is my relevant code which cause the problem according to the breakpoint:

```<code>[tableviewSupport registerNib:[UINib nibWithNibName:@"HotelCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:CustomCellCId];
</code>```

答: In my case I set a property with name class (for eg: @property (strong, nonatomic) IBOutlet UILabel *class) in tableviewcell, this give above mention error , then name "class" is not objective c type, change (class = classabc) resolve above issue.</p>

Body:
I'm using a custom UITableViewCell. When I try to run my code, I got this exception stack and I can't understand the source of the problem:

terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid nib registered for identifier ((null)) - nib must contain exactly one top level object which must be a UITableViewCell instance'

Please note I am not using Storyboard.

EDIT:

This is my relevant code which cause the problem according to the breakpoint:

[tableviewSupport registerNib:[UINib nibWithNibName:@"HotelCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:CustomCellCId];


问:
Tags are missing from my GitHub testing project
I am working with GitFlow , i have updated tags which i can see in cmd but not able to see in GitHub page.

GitHub Test Project link

Screen grab of GitHub :

Screen grab of cmd :

Am i missing something ? or need to do some parameter while adding tag .

答:
Assuming that you have created those tags locally on your machine, you will need to push these up to GitHub.  This can be done by running the command:

```<code>git push --tags
</code>```

You can find more information about this here specifically in the Sharing Tags section.

By default, the git push command doesn’t transfer tags to remote servers. You will have to explicitly push tags to a shared server after you have created them. This process is just like sharing remote branches

Body:
Assuming that you have created those tags locally on your machine, you will need to push these up to GitHub.  This can be done by running the command:

git push --tags

You can find more information about this here specifically in the Sharing Tags section.

By default, the git push command doesn’t transfer tags to remote servers. You will have to explicitly push tags to a shared server after you have created them. This process is just like sharing remote branches


问:
Hiding a link on click css only
i'm pretty new to coding (just started a free weeks ago with html and css). For a news page i tried to implement "read on" links, similiar to this question here: on click hide this (button link) pure css

However i can't seem to make the link disappear after clicking it.
I got this for my code so far (opening and closing works just fine):

.readmore {
  display: none;
}

article[id*="n"]:target .readmore {
  display: block;
}

article:target .used {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>Text visible after you open the site.

  Link that opens more text and should diappear after clicking

  <article id="n2">
    <div class="readmore">more text
     Closing button
    </div>
  </article>
</article></code>```

I feel like i messed something up big time, but i really can't figure it out.

答:
Just put your link inside the article tag including your id.

.readmore {
  display: none;
}

article[id*="n"]:target .readmore {
  display: block;
}

article[id*="n"]:target .used {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>Text visible after you open the site.

  <article id="n2">
    Link that opens more text and should diappear after clicking
    <div class="readmore">more text
      Closing button
    </div>
  </article>
</article></code>```

Title: Hiding a link on click css only

Body:
i'm pretty new to coding (just started a free weeks ago with html and css). For a news page i tried to implement "read on" links, similiar to this question here: on click hide this (button link) pure css

However i can't seem to make the link disappear after clicking it.
I got this for my code so far (opening and closing works just fine):

.readmore {
  display: none;
}

article[id*="n"]:target .readmore {
  display: block;
}

article:target .used {
  display: none;
}

Text visible after you open the site.

  Link that opens more text and should diappear after clicking

more text
     Closing button

I feel like i messed something up big time, but i really can't figure it out.

Body:
Just put your link inside the article tag including your id.

.readmore {
  display: none;
}

article[id*="n"]:target .readmore {
  display: block;
}

article[id*="n"]:target .used {
  display: none;
}

<article>Text visible after you open the site.

  <article id="n2">
    <a href="#n2" class="used">Link that opens more text and should diappear after clicking</a>
    <div class="readmore">more text
      <a href="#back">Closing button</a>
    </div>
  </article>
</article>


问:
Hive Join on String returns no matching
I am trying to run a simple join on string values but getting no matching rows. However all the values are the same in both the tables

```<code>select l2.word,d.polarity from l2 join  dictionary d on (l2.word=d.word);

L2 table :
realtimesession_id      bigint                  None
word                    string                  None

Dictionary table :
realtimesession_id      bigint                  None
word                    string                  None
</code>```

I tried setting set hive.auto.convert.join=true;
but still no records matching. Please someone help.

答:
Joining on strings is not the best practice, although if needed you should use:

select l2.word,d.polarity from l2 join dictionary d on (l2.word rlike d.word)

Title: Hive Join on String returns no matching

Body:
I am trying to run a simple join on string values but getting no matching rows. However all the values are the same in both the tables

select l2.word,d.polarity from l2 join  dictionary d on (l2.word=d.word);

L2 table :
realtimesession_id      bigint                  None
word                    string                  None

Dictionary table :
realtimesession_id      bigint                  None
word                    string                  None

I tried setting set hive.auto.convert.join=true;
but still no records matching. Please someone help.


问:
Is there any way to put malicious code into a regular expression?
I want to add regular expression search capability to my public web page. Other than HTML encoding the output, do I need to do anything to guard against malicious user input?

Google searches are swamped by people solving the converse problem-- using regular expressions to detect malicious input--which I'm not interested in. In my scenario, the user input is a regular expression.

I'll be using the Regex library in .NET (C#).

答: Adding to tchrist's excellent answer: the same Russ Cox who wrote the "Regular Expression" page has also released code! re2 is a C++ library which guarantees O(length_of_regex) runtime and configurable memory-use limit. It's used within Google so that you can type a regex into google code search -- meaning that it's been battle tested.</p>

ContentLicense: CC BY-SA 2.5


问:
CodeLens not showing references
CodeLens stopped working for some reason in project solution that I'm dealing nowadays.  It is not showing references instead "- references".  However, when I open up Visual Studio with another project It works like charm.I can confirm that CodeLens is enabled. Do you have any idea to make it work?</p>

答:
I tried most of the solutions above without luck, as I also saw this problem. On top, certain newly added classes were showing up as white/black (regular text) in Visual Studio.

Changing to Release typically helped, but wasn't a long-term solution.
However, this helped on both issues - verified on another machine. Maybe some of the steps can be left out.

Close all document tabs

Clean solution

Right click on solution, click "Enable Lightweight Solution Load"

Close solution

Reopen solution

Right click on solution, click "Disable Lightweight Solution Load"

Close solution

Reopen solution

Rebuild

Title: CodeLens not showing references


问:
Error when trying to connect to SQL database
I am trying to make a connection with my SQL database using python pymssql but when I run this code:

```<code>server = getenv("DESKTOP-O7QRHV2\SQLEXPRESS")
user = getenv("DESKTOP-O7QHRV2\John")
password = getenv("Password")
database = getenv("eerc")

print(server, user, password, database)
conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor()

cursor.execute("SELECT * FROM constructors")
row = cursor.fetchone()

conn.close()
</code>```

I get this error:

TypeError: argument of type 'NoneType' is not iterable

Unclosed client session

client_session: aiohttp.client.ClientSession object at 0x00000269E1804358>

答:
Most likely your select returns 0 row. You should do a check on the return value of fetchone before trying to iterate it.

You can try to print(row) to see if your query return some data or None for no more data.

Body:
I am trying to make a connection with my SQL database using python pymssql but when I run this code:

server = getenv("DESKTOP-O7QRHV2\SQLEXPRESS")
user = getenv("DESKTOP-O7QHRV2\John")
password = getenv("Password")
database = getenv("eerc")

print(server, user, password, database)
conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor()

cursor.execute("SELECT * FROM constructors")
row = cursor.fetchone()

conn.close()

I get this error:

TypeError: argument of type 'NoneType' is not iterable

Unclosed client session

client_session: aiohttp.client.ClientSession object at 0x00000269E1804358>


问:
Team City Build and Octopus deploy
Team city is often used for building and then use Octopus for deploy. I wonder if I can use a successful octopus deploy to trigger a team city build? If it is possible, how to do this? Thanks. </p>

答:
You could simply add a script step at the end of your deployment which would call the TeamCity URL to trigger a build.

There appears that there is also a community step in the library for doing a HTTP GET or HTTP POST.

Ensure you set the Run Condition to Success so that it will only be triggered when the full deployment has been completed.

Title: Team City Build and Octopus deploy


问:
Test a controller in .Net Core always returns false?
I write the following XUnit test to test a .Net Core WebApi controller's action:

```<code>namespace VistaBest.XUnitTest.Api.Test
{
    public class Account_UnitTest
    {
        [Fact]
        public void ValidateUserTest()
        {
            const string username = "admin";
            const string password = "admin";
            var usersBusinessObjectMock = new Mock<IUsersBusinessObject>();
            usersBusinessObjectMock.Setup(service => service.ValidateUser(username, password)).Returns(() => true);
            var controller = new AccountController(usersBusinessObjectMock.Object);
            var actionResult = controller.ValidateUser(new LoginModel
            {
                Username = username,
                Password = password
            });
            var okObjectResult = Assert.IsType<OkObjectResult>(actionResult);
            var result = okObjectResult.Value as bool?;
            Assert.True(result);
        }
    }
}
</code>```

AccountController:

```<code>namespace VistaBest.Api.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IUsersBusinessObject _usersBusinessObject;
        public AccountController(IUsersBusinessObject usersBusinessObject)
        {
            _usersBusinessObject = usersBusinessObject;
        }

        [HttpPost]
        public IActionResult ValidateUser(LoginModel model)
        {
            if(!ModelState.IsValid) return BadRequest(ModelState);
            return Ok(_usersBusinessObject.ValidateUser(model.Username, model.Password.ToMd5Hash()));
        }
    }
}
</code>```

IUsersBusinessObject:

```<code>namespace VistaBest.Data.BusinessObjects
{
    public interface IUsersBusinessObject
    {
        bool ValidateUser(string username, string password);
        UserModel SelectByUsername(string username);
    }

    public class UsersBusinessObject : BaseBusinessObject, IUsersBusinessObject
    {
        public UsersBusinessObject(IDbConnection connection) : base(connection)
        {

        }

        private const string TableName = "Users";

        public bool ValidateUser(string username, string password)
        {
            var query = $"SELECT COUNT(*) FROM [{TableName}] WHERE UserName = @username and Password = @password";
            return DbConnection.QueryFirst<int>(query, new { username, password }) == 1;
        }
}
</code>```

As you see I said usersBusinessObjectMock must return true:

```<code>usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password))
    .Returns(() => true);
</code>```

But var result = okObjectResult.Value as bool?; is always false

What's wrong?

答:
After reading your code like 10 minutes, as this error is really hard to find. You did everything right...

```<code>        var okObjectResult = Assert.IsType<OkObjectResult>(actionResult);
        var result = okObjectResult.Value as bool?;
        Assert.True(result);
</code>```

But here is the error...

var is dangerous...
your variable okObjectResult is not from type OkObjectResult... that's why your assert is never true...
Im sure you mean't to type

```<code>Assert.IsType<OkObjectResult>(actionResult);
var okObjectResult = (OkObjectResult) actionResult;
</code>```

Body:
I write the following XUnit test to test a .Net Core WebApi controller's action:

namespace VistaBest.XUnitTest.Api.Test
{
    public class Account_UnitTest
    {
        [Fact]
        public void ValidateUserTest()
        {
            const string username = "admin";
            const string password = "admin";
            var usersBusinessObjectMock = new Mock<IUsersBusinessObject>();
            usersBusinessObjectMock.Setup(service => service.ValidateUser(username, password)).Returns(() => true);
            var controller = new AccountController(usersBusinessObjectMock.Object);
            var actionResult = controller.ValidateUser(new LoginModel
            {
                Username = username,
                Password = password
            });
            var okObjectResult = Assert.IsType<OkObjectResult>(actionResult);
            var result = okObjectResult.Value as bool?;
            Assert.True(result);
        }
    }
}

AccountController:

namespace VistaBest.Api.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IUsersBusinessObject _usersBusinessObject;
        public AccountController(IUsersBusinessObject usersBusinessObject)
        {
            _usersBusinessObject = usersBusinessObject;
        }

        [HttpPost]
        public IActionResult ValidateUser(LoginModel model)
        {
            if(!ModelState.IsValid) return BadRequest(ModelState);
            return Ok(_usersBusinessObject.ValidateUser(model.Username, model.Password.ToMd5Hash()));
        }
    }
}

IUsersBusinessObject:

namespace VistaBest.Data.BusinessObjects
{
    public interface IUsersBusinessObject
    {
        bool ValidateUser(string username, string password);
        UserModel SelectByUsername(string username);
    }

    public class UsersBusinessObject : BaseBusinessObject, IUsersBusinessObject
    {
        public UsersBusinessObject(IDbConnection connection) : base(connection)
        {

        }

        private const string TableName = "Users";

        public bool ValidateUser(string username, string password)
        {
            var query = $"SELECT COUNT(*) FROM [{TableName}] WHERE UserName = @username and Password = @password";
            return DbConnection.QueryFirst<int>(query, new { username, password }) == 1;
        }
}

As you see I said usersBusinessObjectMock must return true:

usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password))
    .Returns(() => true);

But var result = okObjectResult.Value as bool?; is always false

What's wrong?

Body:
After reading your code like 10 minutes, as this error is really hard to find. You did everything right...

        var okObjectResult = Assert.IsType<OkObjectResult>(actionResult);
        var result = okObjectResult.Value as bool?;
        Assert.True(result);

But here is the error...

var is dangerous...
your variable okObjectResult is not from type OkObjectResult... that's why your assert is never true...
Im sure you mean't to type

Assert.IsType<OkObjectResult>(actionResult);
var okObjectResult = (OkObjectResult) actionResult;


问:
FOSUserBundle - perform function upon initial login
I have a Symfony 3 application with user management via FOSUserBundle. I want to implement a Listener class that checks for an initial user login, by checking the user's "last_login" value. While I did read the article on event subscribers, I struggle to find out when exactly the last_login value is updated.
Is there anyone with such knowledge, or does anyone know a better approach regarding a user's initial login?</p>

答:
Symfony and FOSUserBundle have events for that. Even FOSUserBundle has an event subscriber for those events

```<code>/**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::SECURITY_IMPLICIT_LOGIN => 'onImplicitLogin',
            SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
        );
    }
</code>```

you could subscribe for those events and make your own logic. There is no such thibg as initial login in symfony, you need to manage by your self.

Subscribe to the events and try something like this:

```<code>public function onSecurityInteractiveLogin(InteractiveLoginEvent $event){

    $user = $event->getAuthenticationToken()->getUser();
    //some logic to check the user
    if(!$user->getLastLogin()){
    //its my first login!!! do what ever you want here
    }else{
        //I have already logged before so just pass
    }
}
</code>```

Also you need to change your subscriber priority to -10 or something like that to catch the event before FOSUserBundle or you will be passing always.

Hope it helps

Body:
Symfony and FOSUserBundle have events for that. Even FOSUserBundle has an event subscriber for those events

/**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::SECURITY_IMPLICIT_LOGIN => 'onImplicitLogin',
            SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
        );
    }

you could subscribe for those events and make your own logic. There is no such thibg as initial login in symfony, you need to manage by your self.

Subscribe to the events and try something like this:

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event){

    $user = $event->getAuthenticationToken()->getUser();
    //some logic to check the user
    if(!$user->getLastLogin()){
    //its my first login!!! do what ever you want here
    }else{
        //I have already logged before so just pass
    }
}

Also you need to change your subscriber priority to -10 or something like that to catch the event before FOSUserBundle or you will be passing always.

Hope it helps


问:
Why does adding and subtracting two #define'd macros not work on iPhone / Objective-c
In my iPhone app, I have this in my .h file

```<code>#define ORIENTATION_IS_PORTRAIT UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])
#define FULLSCREEN_MODE         ORIENTATION_IS_PORTRAIT?460:300
#define AD_HEIGHT               ORIENTATION_IS_PORTRAIT?50:32
#define FULLSCREEN_MODE_WITH_AD FULLSCREEN_MODE - AD_HEIGHT //doesn't work
</code>```

To sum it up, I have a macro to detect the orientation. I have another for the height of my UIWebView when it is in full screen mode (activated by a button press). I need to keep the ad at the bottom. However, to get the height of the UIWebView minus the ad height will only return the AD_HEIGHT.

For addition, (FULLSCREEN_MODE + AD_HEIGHT) returns the FULLSCREEN_MODE only.

Also, when using constants, where exactly do I put them. I searched and could only find answers like "in the .m file", but where??

答: Avoid macros. Define functions. You can declare them inline.

Body:
In my iPhone app, I have this in my .h file

#define ORIENTATION_IS_PORTRAIT UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])
#define FULLSCREEN_MODE         ORIENTATION_IS_PORTRAIT?460:300
#define AD_HEIGHT               ORIENTATION_IS_PORTRAIT?50:32
#define FULLSCREEN_MODE_WITH_AD FULLSCREEN_MODE - AD_HEIGHT //doesn't work

To sum it up, I have a macro to detect the orientation. I have another for the height of my UIWebView when it is in full screen mode (activated by a button press). I need to keep the ad at the bottom. However, to get the height of the UIWebView minus the ad height will only return the AD_HEIGHT.

For addition, (FULLSCREEN_MODE + AD_HEIGHT) returns the FULLSCREEN_MODE only.

Also, when using constants, where exactly do I put them. I searched and could only find answers like "in the .m file", but where??


问:
Yii Change field name
I want to rename the field. Code is here

```<code> [['name'], 'unique', 'message' => 'This Make already exists'],
</code>```

output

```<code>[
{
    "field": "name",
    "message": "This Make already exists"
}
]
</code>```

how i change field? Result

```<code>"field" : "make"
</code>```

答:
Using fields(). In your model override fields() function as follows:

```<code>public function fields()
{
    return['make'=>'name'];
}
</code>```

This will change the name of the field from name to make but your name field will be the only field returned. You can do all the tricks you want to append to the fields returned, or change them using this function though. To know more about fields check: http://www.yiiframework.com/doc-2.0/yii-base-model.html#fields()-detail

Title: Yii Change field name

Body:
I want to rename the field. Code is here

 [['name'], 'unique', 'message' => 'This Make already exists'],

output

[
{
    "field": "name",
    "message": "This Make already exists"
}
]

how i change field? Result

"field" : "make"

Body:
Using fields(). In your model override fields() function as follows:

public function fields()
{
    return['make'=>'name'];
}

This will change the name of the field from name to make but your name field will be the only field returned. You can do all the tricks you want to append to the fields returned, or change them using this function though. To know more about fields check: http://www.yiiframework.com/doc-2.0/yii-base-model.html#fields()-detail


问:
How to print horizontally instead of vertically?
I wrote a script that is supposed to print an answer to a specific input horizontally.

For example if the input is:

```<code>TTACTGGCAT
</code>```

It should print:

```<code>TTACTGGCAT
AATGACCGTA
</code>```

My code:

```<code>x = 0
n = input("Insert DNA seqence: ")
print(n.upper())
while x < len(n):
  if 'T' in n[x]:
    print('A')
  if 'G' in n[x]:
    print('C')
  if 'C' in n[x]:
    print('G')
  if 'A' in n[x]:
    print('T')
  x = x + 1
</code>```

答: You should concat everything in a string and after the loops end print it.</p>

Body:
I wrote a script that is supposed to print an answer to a specific input horizontally.

For example if the input is:

TTACTGGCAT

It should print:

TTACTGGCAT
AATGACCGTA

My code:

x = 0
n = input("Insert DNA seqence: ")
print(n.upper())
while x < len(n):
  if 'T' in n[x]:
    print('A')
  if 'G' in n[x]:
    print('C')
  if 'C' in n[x]:
    print('G')
  if 'A' in n[x]:
    print('T')
  x = x + 1


问:
Join/merge multiple NetCDF files using xarray
I have a folder with NetCDF files from 2006-2100, in ten year blocks (2011-2020, 2021-2030 etc).

I want to create a new NetCDF file which contains all of these files joined together. So far I have read in the files:

```<code>ds = xarray.open_dataset('Path/to/file/20062010.nc')
ds1 = xarray.open_dataset('Path/to/file/20112020.nc')
etc.
</code>```

Then merged these like this:

```<code>dsmerged = xarray.merge([ds,ds1])
</code>```

This works, but is clunky and there must be a simpler way to automate this process, as I will be doing this for many different folders full of files. Is there a more efficient way to do this?

EDIT:

Trying to join these files using glob:

```<code>for filename in glob.glob('path/to/file/.*nc'):
    dsmerged = xarray.merge([filename])
</code>```

Gives the error:

```<code>AttributeError: 'str' object has no attribute 'items'
</code>```

This is reading only the text of the filename, and not the actual file itself, so it can't merge it. How do I open, store as a variable, then merge without doing it bit by bit?

答:
If you are looking for a clean way to get all your datasets merged together, you can use some form of list comprehension and the xarray.merge function to get it done. The following is an illustration:

```<code>ds = xarray.merge([xarray.open_dataset(f) for f in glob.glob('path/to/file/.*nc')])
</code>```

In response to the out of memory issues you encountered, that is probably because you have more files than the python process can handle. The best fix for that is to use the xarray.open_mfdataset function, which actually uses the library dask under the hood to break the data into smaller chunks to be processed. This is usually more memory efficient and will often allow you bring your data into python. With this function, you do not need a for-loop; you can just pass it a string glob in the form "path/to/my/files/*.nc". The following is equivalent to the previously provided solution, but more memory efficient:

```<code>ds = xarray.open_mfdataset('path/to/file/*.nc')
</code>```

I hope this proves useful.

Body:
I have a folder with NetCDF files from 2006-2100, in ten year blocks (2011-2020, 2021-2030 etc).

I want to create a new NetCDF file which contains all of these files joined together. So far I have read in the files:

ds = xarray.open_dataset('Path/to/file/20062010.nc')
ds1 = xarray.open_dataset('Path/to/file/20112020.nc')
etc.

Then merged these like this:

dsmerged = xarray.merge([ds,ds1])

This works, but is clunky and there must be a simpler way to automate this process, as I will be doing this for many different folders full of files. Is there a more efficient way to do this?

EDIT:

Trying to join these files using glob:

for filename in glob.glob('path/to/file/.*nc'):
    dsmerged = xarray.merge([filename])

Gives the error:

AttributeError: 'str' object has no attribute 'items'

This is reading only the text of the filename, and not the actual file itself, so it can't merge it. How do I open, store as a variable, then merge without doing it bit by bit?

Body:
If you are looking for a clean way to get all your datasets merged together, you can use some form of list comprehension and the xarray.merge function to get it done. The following is an illustration:

ds = xarray.merge([xarray.open_dataset(f) for f in glob.glob('path/to/file/.*nc')])

In response to the out of memory issues you encountered, that is probably because you have more files than the python process can handle. The best fix for that is to use the xarray.open_mfdataset function, which actually uses the library dask under the hood to break the data into smaller chunks to be processed. This is usually more memory efficient and will often allow you bring your data into python. With this function, you do not need a for-loop; you can just pass it a string glob in the form "path/to/my/files/*.nc". The following is equivalent to the previously provided solution, but more memory efficient:

ds = xarray.open_mfdataset('path/to/file/*.nc')

I hope this proves useful.


问:
Try-Catch-Finally Block
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

```<code>import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}
</code>```

Any Help Please

答: finally itself cannot handle any exception. So when using try{} finally then the code inside try should either not be raising any exception or your method must be throwing the exception.</p>

Title: Try-Catch-Finally Block

Body:
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}

Any Help Please


答:
Using this you can achieve what you want.....you have added id inner article which you have to give parent artical and change css

```<code>.readmore {
  display: none;
}

#n2:target .readmore {
  display: block;
}

#n2:target .used {
  display: none;
}
</code>```

.readmore {
  display: none;
}

#n2:target .readmore {
  display: block;
}

#n2:target .used {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article id="n2">Text visible after you open the site.

  Link that opens more text and should diappear after clicking

  <article>
    <div class="readmore">more text
     Closing button
    </div>
  </article>
</article></code>```

Title: Hiding a link on click css only

Body:
Using this you can achieve what you want.....you have added id inner article which you have to give parent artical and change css

.readmore {
  display: none;
}

#n2:target .readmore {
  display: block;
}

#n2:target .used {
  display: none;
}

.readmore {
  display: none;
}

#n2:target .readmore {
  display: block;
}

#n2:target .used {
  display: none;
}

<article id="n2">Text visible after you open the site.

  <a href="#n2" class="used">Link that opens more text and should diappear after clicking</a>

  <article>
    <div class="readmore">more text
     <a href="#back">Closing button</a>
    </div>
  </article>
</article>


问:
Updated Android Studio - Firebase Auth Fails
Everything worked before I updated Android Studio, Android Support Repository, Google Play Services, and Google Repository today. Now I can't get past my login screen. As I mentioned in the title, I'm using Firebase for authentication and data storage.

I'm also using an emulator: Nexus 6p API 23

Here's the error that I get when I try to sign in

```<code>03-05 13:39:50.689 2790-2852/alodia.medremind W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
03-05 13:39:50.698 2790-2852/alodia.medremind W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10298000 but found 10084470
</code>```

Here's my project build.gradle:

```<code>buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}

allprojects {
repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Here's my app build.gradle:

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "alodia.medremind"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.github.paolorotolo:appintro:4.1.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.google.firebase:firebase-core:10.2.0'
compile "com.google.firebase:firebase-auth:10.2.0"
compile "com.google.firebase:firebase-database:10.2.0"
compile "com.google.firebase:firebase-storage:10.2.0"

compile 'com.firebaseui:firebase-ui-database:1.2.0'
compile 'org.parceler:parceler-api:1.1.1'

compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
testCompile 'junit:junit:4.12'
apt 'org.parceler:parceler:1.1.1'
}
apply plugin: 'com.google.gms.google-services'
</code>```

It'd be great to be able to fix this issue, but I mostly want to know the why behind this problem. I'm fairly new to Android and I'm sure that I misunderstand a lot of basic concepts.

答: i just solved my problem bro, i think you just need re-sync the firebase, follow this step click tab Tools -> firebase -> choose 1 of the firebase feature -> if the button connected is in the gray color, you have to re-sync the firebase, it will update the firebase configuration to the latest version. hope it will help.</p>

Body:
Everything worked before I updated Android Studio, Android Support Repository, Google Play Services, and Google Repository today. Now I can't get past my login screen. As I mentioned in the title, I'm using Firebase for authentication and data storage.

I'm also using an emulator: Nexus 6p API 23

Here's the error that I get when I try to sign in

03-05 13:39:50.689 2790-2852/alodia.medremind W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
03-05 13:39:50.698 2790-2852/alodia.medremind W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10298000 but found 10084470

Here's my project build.gradle:

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}

allprojects {
repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Here's my app build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "alodia.medremind"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.github.paolorotolo:appintro:4.1.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.google.firebase:firebase-core:10.2.0'
compile "com.google.firebase:firebase-auth:10.2.0"
compile "com.google.firebase:firebase-database:10.2.0"
compile "com.google.firebase:firebase-storage:10.2.0"

compile 'com.firebaseui:firebase-ui-database:1.2.0'
compile 'org.parceler:parceler-api:1.1.1'

compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
testCompile 'junit:junit:4.12'
apt 'org.parceler:parceler:1.1.1'
}
apply plugin: 'com.google.gms.google-services'

It'd be great to be able to fix this issue, but I mostly want to know the why behind this problem. I'm fairly new to Android and I'm sure that I misunderstand a lot of basic concepts.


问:
python key in dict.keys() performance for large dictionaries
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

```<code>dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]
</code>```

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

Body:
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

Body: your_dict.setdefault(value.key, []).append(value.val)


问:
Rotating simulator
I don't find any button or shortcut to rotate the UWP simulator on VS 2017.

I read through the documentation, but none of the buttons (hand or mouse pointer icons) are shown for me.
What I see is simply a window in which my app is run, and it shows the number 000 000 in white on black background.

How can I rotate the simulator?

答:
Based on your description you're running the app on Local Machine and not the Simulator.

Make sure that you have checked the Simulator in this dropdown menu

and then press F5 on your keyboard. You should then be able to see all those buttons.

Title: Rotating simulator


问:
How to string format subprocess output?
Below is my nslookup result using subprocess module in Python.

b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\nName:
www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n\t
216.58.197.68\r\n\r\n'
```

<p>Could someone please help me to format the result as below.</p>

<pre class="lang-none prettyprint-override"><code>Server: server.internal
Name: www.google.com
DNS:  192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68
</code>```

答:
You could use Python's unicode_escape to help convert it. The result could then be split into lines and reassembled as follows:

```<code>nslookup = b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\nName: www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n\t216.58.197.68\r\n\r\n'
lines = [line.strip('\t').replace('  ', ' ') for line in nslookup.decode('unicode_escape').splitlines()]
print('\n'.join([lines[0], lines[3], lines[1], '{} , {}'.format(lines[4], lines[5])]))
</code>```

Giving you:

Server: server.internal
Name: www.google.com
Address: 192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68
```

Address: could be replaced by DNS: by a final .replace()

Title: How to string format subprocess output?

Body:
Below is my nslookup result using subprocess module in Python.

b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\nName:
www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n\t
216.58.197.68\r\n\r\n'

Could someone please help me to format the result as below.

Server: server.internal
Name: www.google.com
DNS:  192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68

Body:
You could use Python's unicode_escape to help convert it. The result could then be split into lines and reassembled as follows:

nslookup = b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\nName: www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n\t216.58.197.68\r\n\r\n'
lines = [line.strip('\t').replace('  ', ' ') for line in nslookup.decode('unicode_escape').splitlines()]
print('\n'.join([lines[0], lines[3], lines[1], '{} , {}'.format(lines[4], lines[5])]))

Giving you:

Server: server.internal
Name: www.google.com
Address: 192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68

Address: could be replaced by DNS: by a final .replace()


问:
Changing CSS on disabled selected elements
I have a form with code similar to:

```<code><form class="eng-select" action="action.php" method="POST">
    <select name="position">
        <option value="disabled" disabled selected>Engineer</option>
        <option value="entry-1">John Doe</option>
        <option value="entry-2">David Smith</option>
        <option value="entry-3">Michael Silk</option>
    </select>
</form>
</code>```

Which produces a dropdown like this:

However I would like to change the css color of the disabled selected entry (what the user sees when they load the page - the picture above). Is this possible, and if so what would the proper CSS call be?

I have looked at similar posts for IE here that mention:

```<code>select option [disabled] { background-color: blue; }
</code>```

but this does not work for me (I am using Google Chrome).

To clarify - I would like to change the CSS before the user clicks and opens the dropdown box.

答:
Your CSS must be

```<code>select option[disabled] { background-color: blue; }
</code>```

Without the space after option. It should work better this way.

With the space, it applies to descendants of the option.

Body:
I have a form with code similar to:

<form class="eng-select" action="action.php" method="POST">
    <select name="position">
        <option value="disabled" disabled selected>Engineer</option>
        <option value="entry-1">John Doe</option>
        <option value="entry-2">David Smith</option>
        <option value="entry-3">Michael Silk</option>
    </select>
</form>

Which produces a dropdown like this:

However I would like to change the css color of the disabled selected entry (what the user sees when they load the page - the picture above). Is this possible, and if so what would the proper CSS call be?

I have looked at similar posts for IE here that mention:

select option [disabled] { background-color: blue; }

but this does not work for me (I am using Google Chrome).

To clarify - I would like to change the CSS before the user clicks and opens the dropdown box.

Body:
Your CSS must be

select option[disabled] { background-color: blue; }

Without the space after option. It should work better this way.

With the space, it applies to descendants of the option.


问:
How can I replace the text of this button only
How can I replace the text of this button only. I do not understand the behavior of this button. And this is all the code I came up with to solve this issue

$('.for_whom .close').click(function(z) {

  if ($(this).hasClass('active')) {
    $('body .for .close').removeClass('active');
    $('body .for .close').text('No');

  } else {
    $(this).addClass('active');
    $('body .for .close').not(this).removeClass('active');
    $(this).text('Yes').css('margin-top', '30px');
  }

});```
<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>
<body>
  <div class="for">
    <button class="close">No</button>
  </div>
  <div class="for">
    <button class="close">No</button>
  </div>
  <div class="for">
    <button class="close">No</button>
  </div>
  <div class="for">
    <button class="close">No</button>
  </div>
</body></code>```

答:
Firstly the class of the parent div to the button elements is .for, not .for_whom. This is why your code appears to do nothing.

You can also make the logic more succinct by using toggleClass(), and providing a function to text() which reads if the clicked button already has the .active class. Try this:

var $buttons = $('.for .close').click(function(z) {
  $buttons.not(this).removeClass('active').text('No');
  $(this).text(function() {
    return $(this).hasClass('active') ? 'No' : 'Yes';
  }).toggleClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  margin-top: 30px;
}</code>```

<button class="close">No</button>

<button class="close">No</button>

<button class="close">No</button>

<button class="close">No</button>

```

Body:
How can I replace the text of this button only. I do not understand the behavior of this button. And this is all the code I came up with to solve this issue

$('.for_whom .close').click(function(z) {

  if ($(this).hasClass('active')) {
    $('body .for .close').removeClass('active');
    $('body .for .close').text('No');

  } else {
    $(this).addClass('active');
    $('body .for .close').not(this).removeClass('active');
    $(this).text('Yes').css('margin-top', '30px');
  }

});

    <button class="close">No</button>

    <button class="close">No</button>

    <button class="close">No</button>

    <button class="close">No</button>

Body:
Firstly the class of the parent div to the button elements is .for, not .for_whom. This is why your code appears to do nothing.

You can also make the logic more succinct by using toggleClass(), and providing a function to text() which reads if the clicked button already has the .active class. Try this:

var $buttons = $('.for .close').click(function(z) {
  $buttons.not(this).removeClass('active').text('No');
  $(this).text(function() {
    return $(this).hasClass('active') ? 'No' : 'Yes';
  }).toggleClass('active');
});

.active {
  margin-top: 30px;
}

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

<body>
  <div class="for"><button class="close">No</button></div>
  <div class="for"><button class="close">No</button></div>
  <div class="for"><button class="close">No</button></div>
  <div class="for"><button class="close">No</button></div>
</body>


问:
Selenium internal server error cause by captureNetworkTraffic()?
Essentially, I'm spawning a multitude of selenium client instances which all connect to one selenium server.

Running about 20 at one time works perfectly fine on my box.

I then added a feature that uses the captureNetworkTraffic() method to read the network traffic as JSON so that I can log the stats to each instance's respective run log.

And now, suddenly, if I run anymore than maybe 3 or 4 at one time, they nearly all fail with a lovely "Internal Selenium Server Error"!

I have done several different tries (with different browsers) both with and without the network stats info being logged, and they all point to the same conclusion: I can't run more than 3 or 4 with this feature.

Does anyone perhaps know why this is? I know for sure this is the cause of the failures too for I've isolated the failure to just this single line of code.

Thank you

答:
I'm running a fairly large setup of selenium scripts at my work and I did some time ago changed all the scripts so every single one starts its own Selenium Server dynamically on seperate ports.

First of all I did run in to similar problem as yours where random errors occurs(Under some load Selenium Server does not always handle very well). But the big benfit was to not have to make sure selenium server is running etc, just to fire up the scripts.

Sure, it does use a lot more memory but I rather troubleshooting our own products instead of Selenium Server :)


问:
How to quickly execute a python file on Mac
I'm a beginner of Python and today I learned a new program that can search a place with Google Maps. This is the code:

```<code>import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
    address = ' '.join(sys.argv[1:])
else:
    address = pyperclip.paste()

webbrowser.open('https://www.google.com/maps/place/' + address)
</code>```

My file name is mapit.py and I really want to know that I can execute by only typing, for example,

```<code>mapit New York
</code>```

in the root command line instead of

```<code>Pycharm\......\pythoh3 mapit.py New York
</code>```

I've tried to execute mapit.py New York on Spotlight search, but it didn't work.

答:
I believe what you want to achieve is to register a custom command with your script, right? To do this, you use aliases:

```<code>$ alias mapit="python3 ...\mapit.py"
</code>```

put the real path to the mapit.py instead of '...\mapit.py'

Then you can use the alias as a command:

```<code>$ mapit "New York"
</code>```

Body:
I'm a beginner of Python and today I learned a new program that can search a place with Google Maps. This is the code:

import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
    address = ' '.join(sys.argv[1:])
else:
    address = pyperclip.paste()

webbrowser.open('https://www.google.com/maps/place/' + address)

My file name is mapit.py and I really want to know that I can execute by only typing, for example,

mapit New York

in the root command line instead of

Pycharm\......\pythoh3 mapit.py New York

I've tried to execute mapit.py New York on Spotlight search, but it didn't work.

Body:
I believe what you want to achieve is to register a custom command with your script, right? To do this, you use aliases:

$ alias mapit="python3 ...\mapit.py"

put the real path to the mapit.py instead of '...\mapit.py'

Then you can use the alias as a command:

$ mapit "New York"


问:
How to handle Object References in Entity?
I have the following structure to save to app database:

```<code>@Entity
public class Project{
   @primaryKey
   String id;
   String name;
   [...]
   Country country;
   [...]
}
</code>```

And my Country Entity looks like the following:

```<code>@Entity
public class Country {
    @PrimaryKey
    private String id;
    private String name;
    private String pk;
}
</code>```

Now to my Question: How do I make Room know the Relation between Country and Project Entity?

答:
Please refer the official documentation

https://developer.android.com/reference/android/arch/persistence/room/Relation.html

Body:
I have the following structure to save to app database:

@Entity
public class Project{
   @primaryKey
   String id;
   String name;
   [...]
   Country country;
   [...]
}

And my Country Entity looks like the following:

@Entity
public class Country {
    @PrimaryKey
    private String id;
    private String name;
    private String pk;
}

Now to my Question: How do I make Room know the Relation between Country and Project Entity?


问:
CFEngine 3.5 Oracle JDK promise
CFEngine 3 newbie here.

Am trying to get Oracle JDK installed on an Ubuntu system, how should I script it in CFEngine?

I can do something like this in shell by using PPA provided by webupd8team:

```<code>add-apt-repository ppa:webupd8team/java
apt-get update

echo "Installing JDK 7..."
echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
apt-get install -y oracle-java7-installer
</code>```

Am totally lost doing this in CFEngine. So far I have:

```<code>body common control {
    inputs => { "$(sys.libdir)/stdlib.cf" };
    bundlesequence => { "manage_properties",
                        "manage_jdk"};
}

bundle agent manage_properties {
    vars:
        "prop_pkgs" slist => {"python-software-properties", "software-properties-common"};
        "cmds"      slist => {  "/usr/bin/add-apt-repository ppa:webupd8team/java",
                                "/bin/echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections",
                                "/bin/echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections",
                                "/usr/bin/apt-get update" };

    methods:
        "$(prop_pkgs)"
            handle => "manage_properties",
            comment => "Make sure required properties packages are installed",
            usebundle => package_latest("$(prop_pkgs)");

    commands:
        "$(cmds)"
            comment => "Firing preinstall commands for JDK";
}

bundle agent manage_jdk {
    methods:
        "JDK"
            handle => "manage_jdk",
            comment => "Make sure Java is installed",
            usebundle => package_latest("oracle-java7-installer");
}
</code>```

But the promise fails with following error:

```<code>2014-06-30T14:11:18+0000    error: /default/manage_jdk/methods/'JDK'/default/package_latest/packages/'oracle-java7-installer'[0]: Finished command related to promiser 'oracle-java7-installer' -- an error occurred, returned 100
2014-06-30T14:11:18+0000    error: /default/manage_jdk/methods/'JDK'/default/package_latest/packages/'oracle-java7-installer'[0]: Bulk package schedule execution failed somewhere - unknown outcome for 'oracle-java7-installer'
</code>```

Would appreciate any pointer. Thanks

答:
One thing that I see in your policy is that you are running some commands that require a shell (your piped commands) and your commands promise is not being contained within any shell.

commands:
  "/bin/echo 'Hello World' | grep Hello"
    contain => in_shell;

Also, it seems that you are taking a very imperative view with your pre-commands. CFEngine typically runs policy once every 5 minutes. I would focus more on performing the operations necessary when necessary and try to focus on the state instead of action.

For example your running apt-add-repository unconditionally. Consider under what conditions you actually need to execute the command.

Title: CFEngine 3.5 Oracle JDK promise

Body:
CFEngine 3 newbie here.

Am trying to get Oracle JDK installed on an Ubuntu system, how should I script it in CFEngine?

I can do something like this in shell by using PPA provided by webupd8team:

add-apt-repository ppa:webupd8team/java
apt-get update

echo "Installing JDK 7..."
echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
apt-get install -y oracle-java7-installer

Am totally lost doing this in CFEngine. So far I have:

body common control {
    inputs => { "$(sys.libdir)/stdlib.cf" };
    bundlesequence => { "manage_properties",
                        "manage_jdk"};
}

bundle agent manage_properties {
    vars:
        "prop_pkgs" slist => {"python-software-properties", "software-properties-common"};
        "cmds"      slist => {  "/usr/bin/add-apt-repository ppa:webupd8team/java",
                                "/bin/echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections",
                                "/bin/echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections",
                                "/usr/bin/apt-get update" };

    methods:
        "$(prop_pkgs)"
            handle => "manage_properties",
            comment => "Make sure required properties packages are installed",
            usebundle => package_latest("$(prop_pkgs)");

    commands:
        "$(cmds)"
            comment => "Firing preinstall commands for JDK";
}

bundle agent manage_jdk {
    methods:
        "JDK"
            handle => "manage_jdk",
            comment => "Make sure Java is installed",
            usebundle => package_latest("oracle-java7-installer");
}

But the promise fails with following error:

2014-06-30T14:11:18+0000    error: /default/manage_jdk/methods/'JDK'/default/package_latest/packages/'oracle-java7-installer'[0]: Finished command related to promiser 'oracle-java7-installer' -- an error occurred, returned 100
2014-06-30T14:11:18+0000    error: /default/manage_jdk/methods/'JDK'/default/package_latest/packages/'oracle-java7-installer'[0]: Bulk package schedule execution failed somewhere - unknown outcome for 'oracle-java7-installer'

Would appreciate any pointer. Thanks


问:
How to PHP MySQL query a STRING?
I have a string called $searchquery. $searchquery contains this SQL command:

```<code>SELECT * FROM `videos` WHERE (`Title` LIKE "%query%" OR `Tags` LIKE "%query%")
</code>```

How can I make MySQL execute this command from a PHP page then display the results on PHP page??

I have tried

```<code>$sql = ($searchquery)
</code>```

But dosent seem to work?

答:
Firstly you need to create database connection </p>

```<code><?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    $conn = mysqli_connect($servername, $username, $password, $dbname);

    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

// then execute your query
$sql = "SELECT * FROM `videos` WHERE (`Title` LIKE '%query%' OR `Tags` LIKE '%query%')";
   $result = mysqli_query($conn, $sql);

// and fetch result set
 while($row = mysqli_fetch_assoc($result)) {
   print_r($row);
}
?>
</code>```

Title: How to PHP MySQL query a STRING?

Body:
I have a string called $searchquery. $searchquery contains this SQL command:

SELECT * FROM `videos` WHERE (`Title` LIKE "%query%" OR `Tags` LIKE "%query%")

How can I make MySQL execute this command from a PHP page then display the results on PHP page??

I have tried

$sql = ($searchquery)

But dosent seem to work?

Body:
Firstly you need to create database connection

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    $conn = mysqli_connect($servername, $username, $password, $dbname);

    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

// then execute your query
$sql = "SELECT * FROM `videos` WHERE (`Title` LIKE '%query%' OR `Tags` LIKE '%query%')";
   $result = mysqli_query($conn, $sql);

// and fetch result set
 while($row = mysqli_fetch_assoc($result)) {
   print_r($row);
}
?>


问:
How to call a non-static method from a non-static class using method reference in Java 8?
I have the following class:

```<code>class Book {
    private String genre;
    public Book(String genre) {this.genre = genre;}
    public String getGenre() {return genre;}
    public class BookFilter {
        public boolean isFiction(Book b) {
            return b.getGenre().equals("fiction");
        }
    }
}
</code>```

I have added to books list a few objects of Book class and now I want to filter the stream using method reference. As it is shown in the below code, using lambda expression the code works fine but using method reference, it does not compile.

```<code>books.stream()
    .filter(b->b.new BookFilter().isFiction(b)) //Works fine
    //.filter(new Book().new BookFilter()::isFiction); //Will not compile
</code>```

I know that if the BookFilter was a static nested class, the following line of code would pass compilation without any problem.

```<code>.filter(new Book.BookFilter()::isFiction)
</code>```

How do I call isFiction() method from Book class using method reference?

Thanks in advance!

答:
The reason your remarked filter call doesn't pass compilation is that your Book class has no parameter-less constructor.

If you add to it

```<code>public Book() {}
</code>```

then

```<code>books.stream().filter(new Book().new BookFilter()::isFiction);
</code>```

will pass compilation.

Body:
I have the following class:

class Book {
    private String genre;
    public Book(String genre) {this.genre = genre;}
    public String getGenre() {return genre;}
    public class BookFilter {
        public boolean isFiction(Book b) {
            return b.getGenre().equals("fiction");
        }
    }
}

I have added to books list a few objects of Book class and now I want to filter the stream using method reference. As it is shown in the below code, using lambda expression the code works fine but using method reference, it does not compile.

books.stream()
    .filter(b->b.new BookFilter().isFiction(b)) //Works fine
    //.filter(new Book().new BookFilter()::isFiction); //Will not compile

I know that if the BookFilter was a static nested class, the following line of code would pass compilation without any problem.

.filter(new Book.BookFilter()::isFiction)

How do I call isFiction() method from Book class using method reference?

Thanks in advance!

Body:
The reason your remarked filter call doesn't pass compilation is that your Book class has no parameter-less constructor.

If you add to it

public Book() {}

then

books.stream().filter(new Book().new BookFilter()::isFiction);

will pass compilation.


答:
Room can not have nested entities, you can embedd POJO classes in an entity but it will get flattened into a single table or if you want Country as an entity then you'll have to store county_id in Project entity and index it as foreign key.

More on Embedded fields: https://developer.android.com/reference/android/arch/persistence/room/Embedded.html

More on Foreign key: https://developer.android.com/reference/android/arch/persistence/room/ForeignKey.html

Title: How to handle Object References in Entity?


问:
Best way to select multiple items in iOS?
I'm writing an iOS app in Swift. I want to display a bunch of items (team names) and want the user to select many of them for a league. What's the best way to do this? I could use a picker view, and take each one out as they are selected. I would like to use checkboxes, but there is nothing built in for that. Maybe a table view with multiple checking? Has anyone already done this and have a good method to use?</p>

答:
I think the best/easiest way to do it is with a UITableView and all you have to do is enable multiple cell selection. Then you can retrieve them by using</p>

```<code>table.indexPathsForSelectedRows
</code>```

Body:
I think the best/easiest way to do it is with a UITableView and all you have to do is enable multiple cell selection. Then you can retrieve them by using

table.indexPathsForSelectedRows


问:
Invalid query on a HQL join query with proper syntax
I have a HQL join query as below

```<code>SELECT first FROM FirstTable AS first, SecondTable AS second WHERE second.firstTable = first;
</code>```

This above query returns as Invalid query. But if I use the same above query without the SELECT first it works perfectly fine. I am using the proper syntax as in the documentation. Any idea on what might be the mistake which I am missing or any fix? And I am using the Grails Dynamic finders to run the HQL i.e.,

```<code>FirstTable.findAll(hql.toString(),params)
</code>```

Where hql is a string builder which I am usign to build the query with all the required parameters(param).

The complete error which I get is as below

org.codehaus.groovy.grails.orm.hibernate.exceptions.GrailsQueryException: Invalid query [SELECT first FROM FirstTable AS first, SecondTable AS second WHERE second.firstTable = first group by first.id order by first.id] for domain class [class com.model.FirstTable]

FirstTable has a OneToMany mapping to SecondTable and Secondtable has a OneToOne mapping to FirstTable

答:
You are trying to select whole table as a column, maybe you should try following : </p>

```<code>  SELECT * FROM FirstTable AS first, SecondTable AS second WHERE second.firstTable = first;
</code>```

Body:
I have a HQL join query as below

SELECT first FROM FirstTable AS first, SecondTable AS second WHERE second.firstTable = first;

This above query returns as Invalid query. But if I use the same above query without the SELECT first it works perfectly fine. I am using the proper syntax as in the documentation. Any idea on what might be the mistake which I am missing or any fix? And I am using the Grails Dynamic finders to run the HQL i.e.,

FirstTable.findAll(hql.toString(),params)

Where hql is a string builder which I am usign to build the query with all the required parameters(param).

The complete error which I get is as below

org.codehaus.groovy.grails.orm.hibernate.exceptions.GrailsQueryException: Invalid query [SELECT first FROM FirstTable AS first, SecondTable AS second WHERE second.firstTable = first group by first.id order by first.id] for domain class [class com.model.FirstTable]

FirstTable has a OneToMany mapping to SecondTable and Secondtable has a OneToOne mapping to FirstTable

Body:
You are trying to select whole table as a column, maybe you should try following :

  SELECT * FROM FirstTable AS first, SecondTable AS second WHERE second.firstTable = first;


问:
Is there an easier way to send ENTER key in GNU Screen?
Currently I am using a script to spawn a daemon:

```<code>screen -r user -X stuff "spawn daemon"
screen -r user -X eval "stuff \015"
</code>```

Is there an easier way to send the enter key ("\015"), or in fact a better way of doing this? (I have to use screen.)

I assume that because I'm not attaching the screen, I won't be able to get the outcome/output of the "spawn daemon" command. Is that correct?

答:
I always do it like this:

```<code>screen -r user -X stuff "spawn daemon^M"
</code>```

where I get the ^M by hitting ctrl-v, then Enter, on the command line.  In bash and vim, ctrl-v can be used to escape characters like Enter that would otherwise have a special effect.

Body:
Currently I am using a script to spawn a daemon:

screen -r user -X stuff "spawn daemon"
screen -r user -X eval "stuff \015"

Is there an easier way to send the enter key ("\015"), or in fact a better way of doing this? (I have to use screen.)

I assume that because I'm not attaching the screen, I won't be able to get the outcome/output of the "spawn daemon" command. Is that correct?

Body:
I always do it like this:

screen -r user -X stuff "spawn daemon^M"

where I get the ^M by hitting ctrl-v, then Enter, on the command line.  In bash and vim, ctrl-v can be used to escape characters like Enter that would otherwise have a special effect.


问:
How to create json array in json array codeigniter
I have been searching for the solution on how to create JSON array in JSON object from Mysql query. Need help from any of you.

My source data in mysql:

```<code>Table: parent
--------------------------------------
| id | firstname | lastname | rating |
--------------------------------------
|  1 | John      | Doe      | 9.3    |
|  2 | Marry     | Jane     | 8.5    |
|  3 | Paijo     | Masni    | 9.8    |
--------------------------------------

Table: children
------------------------------
| id |  idparent  | name     |
------------------------------
|  1 |  1         | John A   |
|  2 |  1         | John B   |
|  3 |  1         | John C   |
|  4 |  2         | Jane A   |
|  5 |  2         | Jane B   |
|  6 |  3         | Bang Jo  |
|  7 |  3         | Kak Jo   |
------------------------------
</code>```

My MySQL Query:

Select p.firstname, p.lastname, p.rating, c.name as children

from parent p join children c on p.id = c.idparent

```<code>Output:
-------------------------------------------------
| id | firstname | lastname | rating | children |
-------------------------------------------------
|  1 | John      | Doe      | 9.3    | John A   |
|  1 | John      | Doe      | 9.3    | John B   |
|  1 | John      | Doe      | 9.3    | John C   |
|  2 | Marry     | Jane     | 8.5    | Jane A   |
|  2 | Marry     | Jane     | 8.5    | Jane B   |
|  3 | Paijo     | Masni    | 9.8    | Bang Jo  |
|  3 | Paijo     | Masni    | 9.8    | Kak Jo   |
-------------------------------------------------
</code>```

Here is my output of JSON format that I wanted:

```<code>var profile = [
    {
        "firstname": "John",
        "lastname": "Doe",
        "rating": 9.3,
        "children": [
            "John A",
            "John B",
            "John C"
        ],
        "id": 1
    },
    {
        "firstname": "Marry",
        "lastname": "Jane",
        "rating": 8.5,
        "children": [
            "Jane A",
            "Jane B"
        ],
        "id": 2
    },
    {
        "firstname": "Paijo",
        "lastname": "Masni",
        "rating": 9.8,
        "children": [
            "Bang Jo",
            "Kak Jo"
        ],
        "id": 3
    }
];
</code>```

The one I got stuck from generating the JSON is on the children: [], I want to have an array with double-quote "" separated by comma ',' inside the [].

Thank you.

NB:
Currenty I am using codeigniter for my coding. If you have faced this kind of problem on codeigniter before, I'm looking forward to getting the sharing from you.

答:
I am using NEIL's array structure,

In codeigniter, use the following code at the end for encoding.

$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($your_array));

It will output the following:

"[{\"firstname\":\"John\",\"lastname\":\"Doe\",\"rating\":9.3,\"children\":[\"John A\",\"John B\",\"John C\"],\"id\":1},{\"firstname\":\"Marry\",\"lastname\":\"Jane\",\"rating\":8.5,\"children\":[\"JaneA\",\"JaneB\"],\"id\":2}]"

And in AJAX return, use the $.parseJSON(data) to get your required result.

Body:
I have been searching for the solution on how to create JSON array in JSON object from Mysql query. Need help from any of you.

My source data in mysql:

Table: parent
--------------------------------------
| id | firstname | lastname | rating |
--------------------------------------
|  1 | John      | Doe      | 9.3    |
|  2 | Marry     | Jane     | 8.5    |
|  3 | Paijo     | Masni    | 9.8    |
--------------------------------------

Table: children
------------------------------
| id |  idparent  | name     |
------------------------------
|  1 |  1         | John A   |
|  2 |  1         | John B   |
|  3 |  1         | John C   |
|  4 |  2         | Jane A   |
|  5 |  2         | Jane B   |
|  6 |  3         | Bang Jo  |
|  7 |  3         | Kak Jo   |
------------------------------

My MySQL Query:

Select p.firstname, p.lastname, p.rating, c.name as children

from parent p join children c on p.id = c.idparent

Output:
-------------------------------------------------
| id | firstname | lastname | rating | children |
-------------------------------------------------
|  1 | John      | Doe      | 9.3    | John A   |
|  1 | John      | Doe      | 9.3    | John B   |
|  1 | John      | Doe      | 9.3    | John C   |
|  2 | Marry     | Jane     | 8.5    | Jane A   |
|  2 | Marry     | Jane     | 8.5    | Jane B   |
|  3 | Paijo     | Masni    | 9.8    | Bang Jo  |
|  3 | Paijo     | Masni    | 9.8    | Kak Jo   |
-------------------------------------------------

Here is my output of JSON format that I wanted:

var profile = [
    {
        "firstname": "John",
        "lastname": "Doe",
        "rating": 9.3,
        "children": [
            "John A",
            "John B",
            "John C"
        ],
        "id": 1
    },
    {
        "firstname": "Marry",
        "lastname": "Jane",
        "rating": 8.5,
        "children": [
            "Jane A",
            "Jane B"
        ],
        "id": 2
    },
    {
        "firstname": "Paijo",
        "lastname": "Masni",
        "rating": 9.8,
        "children": [
            "Bang Jo",
            "Kak Jo"
        ],
        "id": 3
    }
];

The one I got stuck from generating the JSON is on the children: [], I want to have an array with double-quote "" separated by comma ',' inside the [].

Thank you.

NB:
Currenty I am using codeigniter for my coding. If you have faced this kind of problem on codeigniter before, I'm looking forward to getting the sharing from you.