问:
CanActivate: Converting Observable<Observable<boolean>> to Observable<boolean>
I have a user settings page that only the owner should have access to. I want to use CanActivate to implement the restriction. CanActivate requires the output to be boolean or the observable of a boolean. However, my code outputs an observable of an observable of a boolean.

```<code>Type 'Observable<Observable<boolean>>' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.
</code>```

Here my code

```<code>@Injectable()
export class UserGuard implements CanActivate {

  constructor(
    private route: ActivatedRoute,
    private userService: UserService
  ) { }

  canActivate() {
    const username = this.route.snapshot.paramMap.get('username');

    return this.userService.authState().map(auth => {
      return this.userService.getByUid(auth.uid).map(user => {
        return user.username === username ? true : false;
      });
    });
  }
}
</code>```

答:
Use .switchMap in order to flatten the observable. Read about it more here: https://www.learnrxjs.io/operators/transformation/switchmap.html

Essentially if you chain .switchMap to a source observable and an inner observable is returned, that observable will be subscribed to and its value emitted rather than the observable itself being emitted:

```<code>return this.userService.authState().switchMap(auth => {
</code>```

In this case you can also flatten your code slightly by chaining .map to the original observable stream.

```<code>return this.userService.authState().switchMap(auth =>
  this.userService.getByUid(auth.uid)
).map(user => user.username === username);
</code>```

Body:
I have a user settings page that only the owner should have access to. I want to use CanActivate to implement the restriction. CanActivate requires the output to be boolean or the observable of a boolean. However, my code outputs an observable of an observable of a boolean.

Type 'Observable<Observable<boolean>>' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.

Here my code

@Injectable()
export class UserGuard implements CanActivate {

  constructor(
    private route: ActivatedRoute,
    private userService: UserService
  ) { }

  canActivate() {
    const username = this.route.snapshot.paramMap.get('username');

    return this.userService.authState().map(auth => {
      return this.userService.getByUid(auth.uid).map(user => {
        return user.username === username ? true : false;
      });
    });
  }
}

Body:
Use .switchMap in order to flatten the observable. Read about it more here: https://www.learnrxjs.io/operators/transformation/switchmap.html

Essentially if you chain .switchMap to a source observable and an inner observable is returned, that observable will be subscribed to and its value emitted rather than the observable itself being emitted:

return this.userService.authState().switchMap(auth => {

In this case you can also flatten your code slightly by chaining .map to the original observable stream.

return this.userService.authState().switchMap(auth =>
  this.userService.getByUid(auth.uid)
).map(user => user.username === username);


来源: stackexchange

问:
Python Dataframe: Remove timestamp from calculated Days field
I calculated a column using the following code:

```<code>df_EVENT5_5['age'] = dt.datetime.now().date() - df_EVENT5_5['dt_old']
    df_EVENT5_5['age_no_days'] = df_EVENT5_5['age'].dt.total_seconds()/ (24 * 60 * 60)
</code>```

The output column contains the timestamp for some reason.

How do I remove the time stamp?

I tried below but didn't work:

```<code>remove_timestamp_col = ['COL_1', 'COL_2']

    for i in remove_timestamp_col:
        df_EVENT5_13[i] = df_EVENT5_13[i].age.days()
</code>```

答:
I think there might be some dates with time stamps in the data, try subtracting the date only:</p>

```<code>df_EVENT5_5['age'] = dt.date.today() - df_EVENT5_5['dt_old'].apply(dt.datetime.date)
#This gives you the days difference as a number
df_EVENT5_5['age_no_days'] = df_EVENT5_5['age'].dt.days
#If you want it to have 'Days' in the end, you can use concatenation:
df_EVENT5_5['age_with_days'] = df_EVENT5_5['age_no_days'].astype('str') + ' Days'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I calculated a column using the following code:

df_EVENT5_5['age'] = dt.datetime.now().date() - df_EVENT5_5['dt_old']
    df_EVENT5_5['age_no_days'] = df_EVENT5_5['age'].dt.total_seconds()/ (24 * 60 * 60)

The output column contains the timestamp for some reason.

How do I remove the time stamp?

I tried below but didn't work:

remove_timestamp_col = ['COL_1', 'COL_2']

    for i in remove_timestamp_col:
        df_EVENT5_13[i] = df_EVENT5_13[i].age.days()

Body:
I think there might be some dates with time stamps in the data, try subtracting the date only:

df_EVENT5_5['age'] = dt.date.today() - df_EVENT5_5['dt_old'].apply(dt.datetime.date)
#This gives you the days difference as a number
df_EVENT5_5['age_no_days'] = df_EVENT5_5['age'].dt.days
#If you want it to have 'Days' in the end, you can use concatenation:
df_EVENT5_5['age_with_days'] = df_EVENT5_5['age_no_days'].astype('str') + ' Days'


问:
Matplotlib legend vertical rotation
Does someone perhaps know if it is possible to rotate a legend on a plot in matplotlib? I made a simple plot with the below code, and edited the graph in paint to show what I want.

```<code>plt.plot([4,5,6], label = 'test')
ax = plt.gca()
ax.legend()
plt.show()
</code>```

答:
I went to a similar problem and solved it by writing the function legendAsLatex that generates a latex code to be used as the label of the y-axis. The function gathers the color, the marker, the line style, and the label provided to the plot function. It requires enabling the latex and loading the required packages. Here is the code to generate your plot with extra curves that use both vertical axis.

```<code>from matplotlib import pyplot as plt
import matplotlib.colors as cor

plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{amsmath} \usepackage{wasysym}'+
    r'\usepackage[dvipsnames]{xcolor} \usepackage{MnSymbol}  \usepackage{txfonts}')

def legendAsLatex(axes, rotation=90) :
    '''Generate a latex code to be used instead of the legend.
       Uses the label, color, marker and linestyle provided to the pyplot.plot.
       The marker and the linestyle must be defined using the one or two character
           abreviations shown in the help of pyplot.plot.
       Rotation of the markers must be multiple of 90.
    '''
    latexLine = {'-':'\\textbf{\Large ---}',
        '-.':'\\textbf{\Large --\:\!$\\boldsymbol{\cdot}$\:\!--}',
        '--':'\\textbf{\Large --\,--}',':':'\\textbf{\Large -\:\!-}'}
    latexSymbol = {'o':'medbullet', 'd':'diamond', 's':'filledmedsquare',
        'D':'Diamondblack', '*':'bigstar', '+':'boldsymbol{\plus}',
        'x':'boldsymbol{\\times}', 'p':'pentagon', 'h':'hexagon',
        ',':'boldsymbol{\cdot}', '_':'boldsymbol{\minus}','<':'LHD',
        '>':'RHD','v':'blacktriangledown', '^':'blacktriangle'}
    rot90=['^','<','v','>']
    di = [0,-1,2,1][rotation%360//90]
    latexSymbol.update({rot90[i]:latexSymbol[rot90[(i+di)%4]] for i in range(4)})
    return ', '.join(['\\textcolor[rgb]{'\
            + ','.join([str(x) for x in cor.to_rgb(handle.get_color())]) +'}{'
            + '$\\'+latexSymbol.get(handle.get_marker(),';')+'$'
            + latexLine.get(handle.get_linestyle(),'') + '} ' + label
                for handle,label in zip(*axes.get_legend_handles_labels())])

ax = plt.axes()
ax.plot(range(0,10), 'b-', label = 'Blue line')
ax.plot(range(10,0,-1), 'sm', label = 'Magenta squares')
ax.set_ylabel(legendAsLatex(ax))

ax2 = plt.twinx()
ax2.plot([x**0.5 for x in range(0,10)],  'ro', label = 'Red circles')
ax2.plot([x**0.5 for x in range(10,0,-1)],'g--', label = 'Green dashed line')
ax2.set_ylabel(legendAsLatex(ax2))

plt.savefig('legend.eps')

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

Figure generated by the code:

Title: Matplotlib legend vertical rotation

Body:
Does someone perhaps know if it is possible to rotate a legend on a plot in matplotlib? I made a simple plot with the below code, and edited the graph in paint to show what I want.

plt.plot([4,5,6], label = 'test')
ax = plt.gca()
ax.legend()
plt.show()

Body:
I went to a similar problem and solved it by writing the function legendAsLatex that generates a latex code to be used as the label of the y-axis. The function gathers the color, the marker, the line style, and the label provided to the plot function. It requires enabling the latex and loading the required packages. Here is the code to generate your plot with extra curves that use both vertical axis.

from matplotlib import pyplot as plt
import matplotlib.colors as cor

plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{amsmath} \usepackage{wasysym}'+
    r'\usepackage[dvipsnames]{xcolor} \usepackage{MnSymbol}  \usepackage{txfonts}')

def legendAsLatex(axes, rotation=90) :
    '''Generate a latex code to be used instead of the legend.
       Uses the label, color, marker and linestyle provided to the pyplot.plot.
       The marker and the linestyle must be defined using the one or two character
           abreviations shown in the help of pyplot.plot.
       Rotation of the markers must be multiple of 90.
    '''
    latexLine = {'-':'\\textbf{\Large ---}',
        '-.':'\\textbf{\Large --\:\!$\\boldsymbol{\cdot}$\:\!--}',
        '--':'\\textbf{\Large --\,--}',':':'\\textbf{\Large -\:\!-}'}
    latexSymbol = {'o':'medbullet', 'd':'diamond', 's':'filledmedsquare',
        'D':'Diamondblack', '*':'bigstar', '+':'boldsymbol{\plus}',
        'x':'boldsymbol{\\times}', 'p':'pentagon', 'h':'hexagon',
        ',':'boldsymbol{\cdot}', '_':'boldsymbol{\minus}','<':'LHD',
        '>':'RHD','v':'blacktriangledown', '^':'blacktriangle'}
    rot90=['^','<','v','>']
    di = [0,-1,2,1][rotation%360//90]
    latexSymbol.update({rot90[i]:latexSymbol[rot90[(i+di)%4]] for i in range(4)})
    return ', '.join(['\\textcolor[rgb]{'\
            + ','.join([str(x) for x in cor.to_rgb(handle.get_color())]) +'}{'
            + '$\\'+latexSymbol.get(handle.get_marker(),';')+'$'
            + latexLine.get(handle.get_linestyle(),'') + '} ' + label
                for handle,label in zip(*axes.get_legend_handles_labels())])

ax = plt.axes()
ax.plot(range(0,10), 'b-', label = 'Blue line')
ax.plot(range(10,0,-1), 'sm', label = 'Magenta squares')
ax.set_ylabel(legendAsLatex(ax))

ax2 = plt.twinx()
ax2.plot([x**0.5 for x in range(0,10)],  'ro', label = 'Red circles')
ax2.plot([x**0.5 for x in range(10,0,-1)],'g--', label = 'Green dashed line')
ax2.set_ylabel(legendAsLatex(ax2))

plt.savefig('legend.eps')

plt.close()

Figure generated by the code:


问:
Relative image path not working(HTML)
I cant seem to get my image to display on my webpage using a relative path. Im using the program "brackets" to do all of my editing before uploading to the webpage. Below is the relative path that i'm using and when I hover over the path the image thumbnail displays. but it still wont display on the page... am I missing anything? please and thank you.   </p>

```<code><img id="01" class ="tn leftcol" width = "150" height = "150"
src=".//Images/IMG_3604.JPG" alt="1" />
</code>```

答: There are two forward slashes. It should be ./Images/xxxxx.png not .//</p>

Title: Relative image path not working(HTML)


问:
Select non empty elements of list in Python
Given:

```<code>a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'

list = (a, b, c, d, e)
</code>```

How can I get a string using all the non empty elements of the list ?

Desired output:

```<code>'aaa,ccc,eee'
</code>```

答:
You can try this one too:

```<code>a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
tup = (a, b, c, d, e)

res = ",".join(filter(lambda i: not i=='', tup))

print(res)
</code>```

The output will be:

```<code>aaa,ccc,eee
</code>```

It is also a good practice not to use list as a variable name, as it is a reserved keyword from Python.

Body:
Given:

a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'

list = (a, b, c, d, e)

How can I get a string using all the non empty elements of the list ?

Desired output:

'aaa,ccc,eee'

Body:
You can try this one too:

a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
tup = (a, b, c, d, e)

res = ",".join(filter(lambda i: not i=='', tup))

print(res)

The output will be:

aaa,ccc,eee

It is also a good practice not to use list as a variable name, as it is a reserved keyword from Python.


问:
using conda environments in simple snakemake workflows
I am wondering how to best - or simplest - use snakemake in conjunction with conda. I am aware of the "--use-conda" option with a yaml-file per rule.
However, for a simple snakemake workflow I think it would be easier to just
(i) activate a single, existing conda environment, (ii) run the snakemake workflow and (iii) deactivate the environment again.

Is this a good and simple strategy at all or what would be the preferred solution?

Would I need to include Snakemake and its dependencies in all of my relevant conda environment(s) or should I rather install snakemake globally?

Can I reference to an existing conda environment rather than providing the conda yaml description?

答:
From my experiences in a Linux environment (Redhat // CentOS) it was very convenient to set a local alias that starts a conda environment, calling it right when you login, and to then work within and run everything from that conda environment.

Works great with the Linux screen functionality.

To run a large batch production, I will use a screen (Linux) and it will quickly copy the existing environment (the conda environment will thus already be loaded) into a new screen. That way you can close the window and still work elsewhere. I found no issues with running the same conda environment (E.g. "source activate myCondaEvn-2017") from 5 or more different terminal sessions.

I always used conda to manage anything running Snakemake. But I actually never needed to use the --conda call in production. It is possible to  nest conda environments, however, the cost of creating a conda environment for each rule (when I had 100's of rules) is too costly. It did allow me to run Python 2 and Python 3 simultaneously, but I actually never used software which required this.


问:
REST web service - is entity framework an overkill?
I'm familiar with the EF and it looks pretty cool. As far as I can see, it is basically a LINQ to SQL with extra functions (like caching, automatic connection handling and so on). However, in my opinion EF is useful for those applications that directly comminicate with the model data (~persistence).

In case of writing a RESTful web service, we are reading and writing objects (for example) in JSON format. The application calls the web service with some data and it returns data back.

That's why I'm actually thinking on not using EF because it looks like an overkill for me. Since I'm not planning to expose the actual model, I would use DTOs instead (both as input and output of a web service call). This means that I have to do the mapping to the underlying model anyway so the EF would be used as a LINQ to SQL wrapper.

Is there anything I'm missing? Is there any feature that would be useful while writing a RESTful web service? is there any benefit from using EF instead of LINQ to SQL?

答:
So the logic here is that you aren't exposing your entities past the data layer, so EF is pointless.

I never expose my EF Entities pass the business layer, just one layer down from the data layer.  I always project them to ViewModels and Models which are just POCOs.  I've seen this in lots of projects.

Rarely do I actually use the entity change tracking features.  By the time a GET/POST has occurred it doesn't make sense to requery the entities on the POST just so you can update them via change tracking.  Instead a direct update makes more sense and avoids an unnecessary roundtrip to the database.

My point being is in what I've seen it most commonly used, the EF models are not exposed past more than one layer in most cases.  This ensures View/UI layers don't accidentally modify EF state or cause lazy loading(which is usually disabled).

However I still get to leverage the great EF/DB mapping layer and EF LINQ queries, which is by far the greatest features of EF.

Most alternatives such as Dapper are just that, a framework for executing queries.

So I wouldn't fallback to just doing ADO.NET or an older query technology just because you aren't using all the features of EF.  You should still use a modern query framework such as EF or Dapper, simply because you are still executing queries.  Just because you aren't exposing the entities doesn't change that.


问:
Invert a Map (String -> List) in Scala
I have a Map[String, List[String]] and I want to invert it. For example, if I have something like

```<code>  "1" -> List("a","b","c")
  "2" -> List("a","j","k")
  "3" -> List("a","c")
</code>```

The result should be

```<code>  "a" -> List("1","2","3")
  "b" -> List("1")
  "c" -> List("1","3")
  "j" -> List("2")
  "k" -> List("2")
</code>```

I've tried this:

```<code>  m.map(_.swap)
</code>```

But it returns a Map[List[String], String]:

```<code>  List("a","b","c") -> "1"
  List("a","j","k") -> "2"
  List("a","c") -> "3"
</code>```

答:
Map inversion is a little more complicated.

```<code>val m = Map("1" -> List("a","b","c")
           ,"2" -> List("a","j","k")
           ,"3" -> List("a","c"))

m flatten {case(k, vs) => vs.map((_, k))} groupBy (_._1) mapValues {_.map(_._2)}
//res0: Map[String,Iterable[String]] = Map(j -> List(2), a -> List(1, 2, 3), b -> List(1), c -> List(1, 3), k -> List(2))
</code>```

Flatten the Map into a collection of tuples. groupBy will create a new Map with the old values as the new keys. Then un-tuple the values by removing the key (previously value) elements.

Title: Invert a Map (String -> List) in Scala

Body:
I have a Map[String, List[String]] and I want to invert it. For example, if I have something like

  "1" -> List("a","b","c")
  "2" -> List("a","j","k")
  "3" -> List("a","c")

The result should be

  "a" -> List("1","2","3")
  "b" -> List("1")
  "c" -> List("1","3")
  "j" -> List("2")
  "k" -> List("2")

I've tried this:

  m.map(_.swap)

But it returns a Map[List[String], String]:

  List("a","b","c") -> "1"
  List("a","j","k") -> "2"
  List("a","c") -> "3"

Body:
Map inversion is a little more complicated.

val m = Map("1" -> List("a","b","c")
           ,"2" -> List("a","j","k")
           ,"3" -> List("a","c"))

m flatten {case(k, vs) => vs.map((_, k))} groupBy (_._1) mapValues {_.map(_._2)}
//res0: Map[String,Iterable[String]] = Map(j -> List(2), a -> List(1, 2, 3), b -> List(1), c -> List(1, 3), k -> List(2))

Flatten the Map into a collection of tuples. groupBy will create a new Map with the old values as the new keys. Then un-tuple the values by removing the key (previously value) elements.


问:
Bukkit Plugin Messaging
I am trying to use the BungeeCord/Bukkit plugin messaging channel to receive data about players (specifically which chat channel they are in), by first sending a plugin message from Bukkit -> Bungee to request that information.
Here's my problem. I need a way to wait for the response from the BungeeCord server (in the form of a plugin message), and then use it once it's recieved.

I used the tutorial here, but the server just crashes because the onPluginMessageReceived doesn't fire when the plugin message is recieved from the Bungee server, so notifyAll doesn't fire.

Here's the code for requesting the information:

```<code>public synchronized Object get(Player p, String... data) {
        sendToBungeeCord(p,"get",data);

        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return obj.get(p);
    }
</code>```

And here's the code for the plugin message being recieved:

```<code>@Override
    public synchronized void onPluginMessageReceived(String channel, Player player, byte[] message) {
        player.sendMessage("return");
        if (channel.equals("BungeeCord")) {
            ByteArrayDataInput in = ByteStreams.newDataInput(message);
            String action = in.readUTF();
            if (action.equals("get")) {
                String dataType = in.readUTF();
                String id = in.readUTF();
                if (dataType.equals("channel")) {
                    obj.put(player,id);
                    this.notifyAll();
                }
            } else if (action.equals("test")) {
                player.sendMessage(in.readUTF());
            }
        }
    }
</code>```

If there is a way to do this without waiting the rest of the server (the rest of the plugin can run while waiting for the response) please help me understand how I go about it.

答:
You should not block the main server thread, but instead just let it keep doing other things while you are waiting for the BungeeCord answer.

You also should NOT use anything async when working with this communication channel since the Spigot API is designed to work only on the main server thread. If you are trying to use it from other threads, then lots of bugs / side effects may appear on the server, which may even cause player data lose or even server crashes in certain situations.

So the solution to your problem would be the following:

Do not block the server while you are waiting for the BungeeCords answer

Process the result of the answer when you got it and not when you requested it

Title: Bukkit Plugin Messaging

Body:
I am trying to use the BungeeCord/Bukkit plugin messaging channel to receive data about players (specifically which chat channel they are in), by first sending a plugin message from Bukkit -> Bungee to request that information.
Here's my problem. I need a way to wait for the response from the BungeeCord server (in the form of a plugin message), and then use it once it's recieved.

I used the tutorial here, but the server just crashes because the onPluginMessageReceived doesn't fire when the plugin message is recieved from the Bungee server, so notifyAll doesn't fire.

Here's the code for requesting the information:

public synchronized Object get(Player p, String... data) {
        sendToBungeeCord(p,"get",data);

        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return obj.get(p);
    }

And here's the code for the plugin message being recieved:

@Override
    public synchronized void onPluginMessageReceived(String channel, Player player, byte[] message) {
        player.sendMessage("return");
        if (channel.equals("BungeeCord")) {
            ByteArrayDataInput in = ByteStreams.newDataInput(message);
            String action = in.readUTF();
            if (action.equals("get")) {
                String dataType = in.readUTF();
                String id = in.readUTF();
                if (dataType.equals("channel")) {
                    obj.put(player,id);
                    this.notifyAll();
                }
            } else if (action.equals("test")) {
                player.sendMessage(in.readUTF());
            }
        }
    }

If there is a way to do this without waiting the rest of the server (the rest of the plugin can run while waiting for the response) please help me understand how I go about it.


问:
Count Case with 2 columns with the same values (Clarified)
Basically I want COUNT a CASE when values are present in 2 columns.

For example:

```<code>SELECT
   COUNT
      (CASE WHEN 1.sample AND 2.sample IN ('a','b','c')
       THEN 1
       ELSE NULL
       END
      )   AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2
...
</code>```

Message:

Conversion failed when converting the varchar value '08:12.06' to data
  type int. Warning: Null value is eliminated by an aggregate or other
  SET operation.

I get what's triggering the error, I just don't know a solution to count the case when values are present in both columns.

答:
Can you try this and see if it works? I think this is what you are looking for.</p>

```<code>SELECT
   SUM
      (CASE WHEN 1.sample IN ('a','b','c') AND 2.sample IN ('a','b','c')
       THEN 1
       ELSE 0
       END
      )   AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2
</code>```

Body:
Basically I want COUNT a CASE when values are present in 2 columns.

For example:

SELECT
   COUNT
      (CASE WHEN 1.sample AND 2.sample IN ('a','b','c')
       THEN 1
       ELSE NULL
       END
      )   AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2
...

Message:

Conversion failed when converting the varchar value '08:12.06' to data
  type int. Warning: Null value is eliminated by an aggregate or other
  SET operation.

I get what's triggering the error, I just don't know a solution to count the case when values are present in both columns.

Body:
Can you try this and see if it works? I think this is what you are looking for.

SELECT
   SUM
      (CASE WHEN 1.sample IN ('a','b','c') AND 2.sample IN ('a','b','c')
       THEN 1
       ELSE 0
       END
      )   AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2


问:
Unable to select options value or text from ui list dropdown in protractor
This is my HTML code:

```<code><div class="chosen-container chosen-container-single" style="width: 240px;" title="">
  <a class="chosen-single" tabindex="-1">
    <span>General Information</span>
    <div>
      <b></b>
    </div>
  </a>
  <div class="chosen-drop">
    <div class="chosen-search">
      <input type="text" autocomplete="off">
    </div>
    <ul class="chosen-results">
      <li class="active-result ng-binding" data-option-array-index="0" style="">Please select an option</li>
      <li class="group-result">General</li>
      <li class="active-result result-selected group-option" data-option-array-index="2" style="">General Information1</li>
      <li class="active-result group-option" data-option-array-index="3" style="">General Information2</li>
      <li class="active-result group-option" data-option-array-index="4" style="">General Information3</li>
      <li class="active-result group-option" data-option-array-index="5" style="">General Information4</li>
      <li class="active-result group-option" data-option-array-index="6" style="">General Information5</li>
      <li class="active-result group-option" data-option-array-index="7" style="">General Information6</li>
      <li class="active-result group-option" data-option-array-index="8" style="">General Information7</li>
      <li class="active-result group-option" data-option-array-index="9" style="">General Information8</li>
      <li class="active-result group-option" data-option-array-index="10" style="">General Information9</li>
      <li class="active-result group-option" data-option-array-index="11" style="">General Information10</li>
    </ul>
  </div>
</div>
</code>```

Able to click on dropdown by

```<code>reportdropdown=element(by.css('a.chosen-single'));
</code>```

Tried with below code :

```<code>reportdropdown.all(by.css("li.active-result.result-selected.ng-binding")).get(1).click();
</code>```

Please suggest solutions to select option by text or index.
Thanks in advance.

答:
For select by text, use cssContainingText.

Also reduce your idetifiers in the locator to the necessary ones

```<code>$('div.chosen-container-single').element(by.cssContainingText("li.active-result"), 'text of option to select').click();
</code>```

As for the index, just replace get(1) with get(index).

```<code>$('div.chosen-container-single').all(by.css("li.active-result")).get(index).click();
</code>```

Or if you want it to be part of the locator:

```<code>$('div.chosen-container-single').element(by.css('li.active-result[data-opion-array-index="'+index+'"]"')).click();
</code>```

UPDATE:
I missed, that your -tag is not parent of
. Therefore replace your reportdropdown with a parent element.

Body:
This is my HTML code:

    General Information

      <input type="text" autocomplete="off">

Please select an option

General

General Information1

General Information2

General Information3

General Information4

General Information5

General Information6

General Information7

General Information8

General Information9

General Information10

Able to click on dropdown by

reportdropdown=element(by.css('a.chosen-single'));

Tried with below code :

reportdropdown.all(by.css("li.active-result.result-selected.ng-binding")).get(1).click();

Please suggest solutions to select option by text or index.
Thanks in advance.

Body:
For select by text, use cssContainingText.

Also reduce your idetifiers in the locator to the necessary ones

$('div.chosen-container-single').element(by.cssContainingText("li.active-result"), 'text of option to select').click();

As for the index, just replace get(1) with get(index).

$('div.chosen-container-single').all(by.css("li.active-result")).get(index).click();

Or if you want it to be part of the locator:

$('div.chosen-container-single').element(by.css('li.active-result[data-opion-array-index="'+index+'"]"')).click();

UPDATE:
I missed, that your <a>-tag is not parent of <ul>. Therefore replace your reportdropdown with a parent element.


问:
Powershell SelectSingleNode on a child node
I'm using Powershell to install an SSIS Project and create a Environment for it.  I am reading the project parameters from the Project.Params XML file to create the environment variables & their values.  I am able to use the following code snippet to read the parameters & their values, but I'd like to use SelectSingleNode instead of the second foreach loop. My XPath skills are not up to it.
Here's the working code:

```<code># load the Params file into memory
[xml]$ParamsDoc = Get-Content -Path $ParamsFilePath

# for each parameter in the Params file, add an environment variable if it doesn't already exist
foreach ($Param in $ParamsDoc.Parameters.Parameter)
{
    $ParamName = $Param.Name

    # use the value in the Params file as the default value for the environment variable
    foreach ($Prop in $Param.Properties.Property)
    {
        if ($Prop.Name -eq 'value')
        {
            $ParamValue = $Prop.InnerText
            break
        }
    }
    AddEnvironmentVariableIfMissing $ParamName $ParamValue
}
</code>```

AddEnvironmentVariableIfMissing is a separate function I've written.  Now, here's the code that doesn't work:

```<code># load the Params file into memory
[xml]$ParamsDoc = Get-Content $ParamsFilePath

$nsMgr = New-Object System.Xml.XmlNamespaceManager($ParamsDoc.NameTable)
$nsMgr.AddNamespace("SSIS", $ParamsDoc.DocumentElement.NamespaceURI)

foreach ($Param in $ParamsDoc.Parameters.Parameter)
{
    $ParamName = $Param.Name

    # NONE of these work!
    $ParamValue = $Param.Properties.SelectSingleNode("SSIS:Property[@Name='Value']",$nsMgr)
    $ParamValue = $Param.Properties.SelectSingleNode("Name[.='Value']",$nsMgr)
    $ParamValue = $Param.Properties.SelectSingleNode("SSIS:Property/Name[.='Value']",$nsMgr)
    $ParamValue = $Param.Properties.Property.SelectSingleNode("Name[.='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Properties/SSIS:Property[@Name='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Properties/SSIS:Property/Name[.='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Property[@Name='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Property/Name[.='Value']",$nsMgr)

    AddEnvironmentVariableIfMissing $ParamName $ParamValue
}
</code>```

What is the correct XPath syntax to get the child node with Name = 'Value'?

Here's a sample of an SSIS Project.params file

```<code><?xml version="1.0"?>
<SSIS:Parameters xmlns:SSIS="www.microsoft.com/SqlServer/SSIS">
  <SSIS:Parameter
    SSIS:Name="Client">
    <SSIS:Properties>
      <SSIS:Property
        SSIS:Name="ID">{144b0266-9e94-4821-bb68-f020436d5df5}</SSIS:Property>
      <SSIS:Property
        SSIS:Name="CreationName"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="Description"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="IncludeInDebugDump">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Required">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Sensitive">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Value">sampleclient</SSIS:Property>
      <SSIS:Property
        SSIS:Name="DataType">18</SSIS:Property>
    </SSIS:Properties>
  </SSIS:Parameter>
  <SSIS:Parameter
    SSIS:Name="MSSQLServer">
    <SSIS:Properties>
      <SSIS:Property
        SSIS:Name="ID">{b4e6c5e1-ef85-4df3-b2dc-db37971d081d}</SSIS:Property>
      <SSIS:Property
        SSIS:Name="CreationName"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="Description"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="IncludeInDebugDump">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Required">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Sensitive">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Value">MSSQLSERVER</SSIS:Property>
      <SSIS:Property
        SSIS:Name="DataType">18</SSIS:Property>
    </SSIS:Properties>
  </SSIS:Parameter>
</SSIS:Parameters>
</code>```

答:
So PetSerAI had the right idea. The namespace needed to be in the XPath syntax, including the Name element.  The two syntax that work are:

```<code>    $ParamValue = $Param.Properties.SelectSingleNode("SSIS:Property[@SSIS:Name='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Properties/SSIS:Property[@SSIS:Name='Value']",$nsMgr)
</code>```

Thank you, PetSerAI !

Body:
I'm using Powershell to install an SSIS Project and create a Environment for it.  I am reading the project parameters from the Project.Params XML file to create the environment variables & their values.  I am able to use the following code snippet to read the parameters & their values, but I'd like to use SelectSingleNode instead of the second foreach loop. My XPath skills are not up to it.
Here's the working code:

# load the Params file into memory
[xml]$ParamsDoc = Get-Content -Path $ParamsFilePath

# for each parameter in the Params file, add an environment variable if it doesn't already exist
foreach ($Param in $ParamsDoc.Parameters.Parameter)
{
    $ParamName = $Param.Name

    # use the value in the Params file as the default value for the environment variable
    foreach ($Prop in $Param.Properties.Property)
    {
        if ($Prop.Name -eq 'value')
        {
            $ParamValue = $Prop.InnerText
            break
        }
    }
    AddEnvironmentVariableIfMissing $ParamName $ParamValue
}

AddEnvironmentVariableIfMissing is a separate function I've written.  Now, here's the code that doesn't work:

# load the Params file into memory
[xml]$ParamsDoc = Get-Content $ParamsFilePath

$nsMgr = New-Object System.Xml.XmlNamespaceManager($ParamsDoc.NameTable)
$nsMgr.AddNamespace("SSIS", $ParamsDoc.DocumentElement.NamespaceURI)

foreach ($Param in $ParamsDoc.Parameters.Parameter)
{
    $ParamName = $Param.Name

    # NONE of these work!
    $ParamValue = $Param.Properties.SelectSingleNode("SSIS:Property[@Name='Value']",$nsMgr)
    $ParamValue = $Param.Properties.SelectSingleNode("Name[.='Value']",$nsMgr)
    $ParamValue = $Param.Properties.SelectSingleNode("SSIS:Property/Name[.='Value']",$nsMgr)
    $ParamValue = $Param.Properties.Property.SelectSingleNode("Name[.='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Properties/SSIS:Property[@Name='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Properties/SSIS:Property/Name[.='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Property[@Name='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Property/Name[.='Value']",$nsMgr)

    AddEnvironmentVariableIfMissing $ParamName $ParamValue
}

What is the correct XPath syntax to get the child node with Name = 'Value'?

Here's a sample of an SSIS Project.params file

<?xml version="1.0"?>
<SSIS:Parameters xmlns:SSIS="www.microsoft.com/SqlServer/SSIS">
  <SSIS:Parameter
    SSIS:Name="Client">
    <SSIS:Properties>
      <SSIS:Property
        SSIS:Name="ID">{144b0266-9e94-4821-bb68-f020436d5df5}</SSIS:Property>
      <SSIS:Property
        SSIS:Name="CreationName"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="Description"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="IncludeInDebugDump">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Required">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Sensitive">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Value">sampleclient</SSIS:Property>
      <SSIS:Property
        SSIS:Name="DataType">18</SSIS:Property>
    </SSIS:Properties>
  </SSIS:Parameter>
  <SSIS:Parameter
    SSIS:Name="MSSQLServer">
    <SSIS:Properties>
      <SSIS:Property
        SSIS:Name="ID">{b4e6c5e1-ef85-4df3-b2dc-db37971d081d}</SSIS:Property>
      <SSIS:Property
        SSIS:Name="CreationName"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="Description"></SSIS:Property>
      <SSIS:Property
        SSIS:Name="IncludeInDebugDump">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Required">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Sensitive">0</SSIS:Property>
      <SSIS:Property
        SSIS:Name="Value">MSSQLSERVER</SSIS:Property>
      <SSIS:Property
        SSIS:Name="DataType">18</SSIS:Property>
    </SSIS:Properties>
  </SSIS:Parameter>
</SSIS:Parameters>

Body:
So PetSerAI had the right idea. The namespace needed to be in the XPath syntax, including the Name element.  The two syntax that work are:

    $ParamValue = $Param.Properties.SelectSingleNode("SSIS:Property[@SSIS:Name='Value']",$nsMgr)
    $ParamValue = $Param.SelectSingleNode("SSIS:Properties/SSIS:Property[@SSIS:Name='Value']",$nsMgr)

Thank you, PetSerAI !


问:
Is there a way to check for an exception without using try/catch in Java?
I am fairly new to Java, I have some code that will act on an array in a loop, and the array changes every loop. Sometimes the code will throw a IndexOutOfBoundsException, when the array is too short. Is there a way for me to only execute code if there is no exception thrown? I know in Javascript I could do something like

```<code>var a = arr[index];
if (!a === null) { //do something }
</code>```

How would I achieve the same effect in Java?

答:
You can only execute code if an exception is not thrown:

```<code>try {
  // Code that may throw an exception...

  // Only execute this if exception isn't thrown.
} catch (SomeException e) {
  // Handle exception.
}
</code>```

But a better strategy is not to cause the exception in the first place. Aside from the ugly syntax above, exceptions are really slow, because they require a full stack trace to be built. By which I mean: they are probably fast enough for many applications, but building that stack trace that you're going to throw away immediately is just wasteful, and faster not to do.

The sort of exception you are talking about here is a runtime exception, which is a type of unchecked exception. Runtime exceptions are supposed to be thrown to indicate a programming error - in this case, that you've not checked if the array index is in bounds.

You can either check this with separate conditions:

```<code>if (i >= 0) {
  if (i < arr.length) {
    // Only execute this if index in bounds
  }
}
</code>```

Or, use &&, which stops evaluating once an operand is false:

```<code>if (i >= 0 && i < arr.length) {
  // ...
}
</code>```

Body:
I am fairly new to Java, I have some code that will act on an array in a loop, and the array changes every loop. Sometimes the code will throw a IndexOutOfBoundsException, when the array is too short. Is there a way for me to only execute code if there is no exception thrown? I know in Javascript I could do something like

var a = arr[index];
if (!a === null) { //do something }

How would I achieve the same effect in Java?

Body:
You can only execute code if an exception is not thrown:

try {
  // Code that may throw an exception...

  // Only execute this if exception isn't thrown.
} catch (SomeException e) {
  // Handle exception.
}

But a better strategy is not to cause the exception in the first place. Aside from the ugly syntax above, exceptions are really slow, because they require a full stack trace to be built. By which I mean: they are probably fast enough for many applications, but building that stack trace that you're going to throw away immediately is just wasteful, and faster not to do.

The sort of exception you are talking about here is a runtime exception, which is a type of unchecked exception. Runtime exceptions are supposed to be thrown to indicate a programming error - in this case, that you've not checked if the array index is in bounds.

You can either check this with separate conditions:

if (i >= 0) {
  if (i < arr.length) {
    // Only execute this if index in bounds
  }
}

Or, use &&, which stops evaluating once an operand is false:

if (i >= 0 && i < arr.length) {
  // ...
}


答:
If you have to go out of a directory, use ../ if the image folder is in the folder you are currently in use nothing.

Src="Images/IMG_3604.JPG"

Your html file is in the same directory.

Src="../Images/IMG_3604.JPG"

Html file is in a subdirectory and you need to go outside of that folder to get to images.

Src="../../Images/IMG_3604.JPG"

Html is in a subdirectory of a subdirectory and you need to go outside of both to get to the Images folder.

Hope this helps.

Title: Relative image path not working(HTML)

Body: I cant seem to get my image to display on my webpage using a relative path. Im using the program "brackets" to do all of my editing before uploading to the webpage. Below is the relative path that i'm using and when I hover over the path the image thumbnail displays. but it still wont display on the page... am I missing anything? please and thank you.


问:
Append vector of unique ptr to another via member function
I want to move a vector of unique ptrs to a vector of unique ptrs I have stored in a class. I have reduced this to a minimum example here:

```<code>#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class A
{
public:
    A() = default;
};

class B
{

public:

    void AddAs(const vector<unique_ptr<A>>& vv)
    {

        vec.insert(vec.end(),
            std::make_move_iterator(vv.begin()),
            std::make_move_iterator(vv.end())
        );
    }

    vector<unique_ptr<A>> vec;
};

int main() {
    vector<unique_ptr<A>> v;
    for(int i=0; i<10; ++i)
    {
        v.push_back(make_unique<A>());
    }
    B b;
    b.AddAs(v);

    return 0;
}
</code>```

https://ideone.com/76iNIM

This trying to follow the answer from Inserting a vector of unique_ptr into another vector

But this doesn't compile as it says that is using the copy operator.

I am sure this is a stupid question, but I am new to C++ and I am struggling to see where the copy is.

Thank you

答:
You cannot move from a vector, that you passed by const reference, as moving requires modification. So change that method to:

```<code>void AddAs(vector<unique_ptr<A>>&& vv)
</code>```

Passing by value will also work:

```<code>void AddAs(vector<unique_ptr<A>> vv)
</code>```

Note you need to change calling code:

```<code>b.AddAs(std::move(v));
</code>```

which is actually good as shows the reader that vector would be moved from.

live example

Body:
I want to move a vector of unique ptrs to a vector of unique ptrs I have stored in a class. I have reduced this to a minimum example here:

#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class A
{
public:
    A() = default;
};

class B
{

public:

    void AddAs(const vector<unique_ptr>& vv)
    {

        vec.insert(vec.end(),
            std::make_move_iterator(vv.begin()),
            std::make_move_iterator(vv.end())
        );
    }

    vector<unique_ptr> vec;
};

int main() {
    vector<unique_ptr> v;
    for(int i=0; i<10; ++i)
    {
        v.push_back(make_unique());
    }
    B b;
    b.AddAs(v);

    return 0;
}

https://ideone.com/76iNIM

This trying to follow the answer from Inserting a vector of unique_ptr into another vector

But this doesn't compile as it says that is using the copy operator.

I am sure this is a stupid question, but I am new to C++ and I am struggling to see where the copy is.

Thank you

Body:
You cannot move from a vector, that you passed by const reference, as moving requires modification. So change that method to:

void AddAs(vector<unique_ptr<A>>&& vv)

Passing by value will also work:

void AddAs(vector<unique_ptr<A>> vv)

Note you need to change calling code:

b.AddAs(std::move(v));

which is actually good as shows the reader that vector would be moved from.

live example


问:
Redirect php page with htaccess
My old domain address is http://www.example.com/viewtopic.php?t=123456

and then I want to redirect all these type of addresses to http://www.newdomain.com/viewtopic.php?t=123456

```<code>RewriteEngine on
RewriteBase /
RewriteRule viewtopic\.php?t=([^/]+)$ http://freeware2010.com/viewtopic.php?t=$1
</code>```

The code does not appear to work.

答:
You want a permanent (301) redirect. Here are a couple of tutorials on how to do it (the first being very verbose and slow-paced, so good for a beginner).

http://www.gnc-web-creations.com/301-redirect.htm

http://www.askapache.com/htaccess/301-redirect-with-mod_rewrite-or-redirectmatch.html

ContentLicense: CC BY-SA 4.0

Title: Redirect php page with htaccess

Body:
My old domain address is http://www.example.com/viewtopic.php?t=123456

and then I want to redirect all these type of addresses to http://www.newdomain.com/viewtopic.php?t=123456

RewriteEngine on
RewriteBase /
RewriteRule viewtopic\.php?t=([^/]+)$ http://freeware2010.com/viewtopic.php?t=$1

The code does not appear to work.

ContentLicense: CC BY-SA 2.5


问:
Convert string to integer type in Go?
I'm trying to convert a string returned from flag.Arg(n) to an int. What is the idiomatic way to do this in Go?

答:
Here are three ways to parse strings into integers, from fastest runtime to slowest:

strconv.ParseInt(...) fastest

strconv.Atoi(...) still very fast

fmt.Sscanf(...) not terribly fast but most flexible

Here's a benchmark that shows usage and example timing for each function:

```<code>package main

import "fmt"
import "strconv"
import "testing"

var num = 123456
var numstr = "123456"

func BenchmarkStrconvParseInt(b *testing.B) {
  num64 := int64(num)
  for i := 0; i < b.N; i++ {
    x, err := strconv.ParseInt(numstr, 10, 64)
    if x != num64 || err != nil {
      b.Error(err)
    }
  }
}

func BenchmarkAtoi(b *testing.B) {
  for i := 0; i < b.N; i++ {
    x, err := strconv.Atoi(numstr)
    if x != num || err != nil {
      b.Error(err)
    }
  }
}

func BenchmarkFmtSscan(b *testing.B) {
  for i := 0; i < b.N; i++ {
    var x int
    n, err := fmt.Sscanf(numstr, "%d", &x)
    if n != 1 || x != num || err != nil {
      b.Error(err)
    }
  }
}
</code>```

You can run it by saving as atoi_test.go and running go test -bench=. atoi_test.go.

goos: darwin
goarch: amd64
BenchmarkStrconvParseInt-8      100000000           17.1 ns/op
BenchmarkAtoi-8                 100000000           19.4 ns/op
BenchmarkFmtSscan-8               2000000          693   ns/op
PASS
ok      command-line-arguments  5.797s
```

Title: Convert string to integer type in Go?

Body:
Here are three ways to parse strings into integers, from fastest runtime to slowest:

strconv.ParseInt(...) fastest

strconv.Atoi(...) still very fast

fmt.Sscanf(...) not terribly fast but most flexible

Here's a benchmark that shows usage and example timing for each function:

package main

import "fmt"
import "strconv"
import "testing"

var num = 123456
var numstr = "123456"

func BenchmarkStrconvParseInt(b *testing.B) {
  num64 := int64(num)
  for i := 0; i < b.N; i++ {
    x, err := strconv.ParseInt(numstr, 10, 64)
    if x != num64 || err != nil {
      b.Error(err)
    }
  }
}

func BenchmarkAtoi(b *testing.B) {
  for i := 0; i < b.N; i++ {
    x, err := strconv.Atoi(numstr)
    if x != num || err != nil {
      b.Error(err)
    }
  }
}

func BenchmarkFmtSscan(b *testing.B) {
  for i := 0; i < b.N; i++ {
    var x int
    n, err := fmt.Sscanf(numstr, "%d", &x)
    if n != 1 || x != num || err != nil {
      b.Error(err)
    }
  }
}

You can run it by saving as atoi_test.go and running go test -bench=. atoi_test.go.

goos: darwin
goarch: amd64
BenchmarkStrconvParseInt-8      100000000           17.1 ns/op
BenchmarkAtoi-8                 100000000           19.4 ns/op
BenchmarkFmtSscan-8               2000000          693   ns/op
PASS
ok      command-line-arguments  5.797s


问:
res.end(result) doesn't display the result on my web page
Calling res.end(result) doesn't display the result on my web page, it is just displayed on the console when I call console.log('result ' + result).

this is my nodejs code:

```<code> const express = require('express')
    const app = express()
    var url = require('url');
    var Web3 = require('web3');

app.get('/', function(req, res) {
            res.writeHead(200, {
                'Content-Type': 'text/html'
            });

            if (typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider);
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://54.00.00.00:3010"));
            }

            if (web3.isConnected()) {

                var abi = JSON.parse('[{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getData","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"uint256"},{"name":"","type":"bytes32"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"Achats","outputs":[{"name":"aName","type":"bytes32"},{"name":"aId","type":"uint256"},{"name":"aDate","type":"bytes32"},{"name":"aValue","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"name","type":"bytes32"},{"name":"iid","type":"uint256"},{"name":"date","type":"bytes32"},{"name":"value","type":"uint256"}],"name":"setData","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]');
                TestContract = web3.eth.contract(abi);
                contractInstance = TestContract.at('0xc08f46fff9fcf082a0d1cebbcc464ca141d2b7d7');

                if (q.opt == 'get' && typeof q.index != "undefined") {
                    contractInstance.getData.call(parseInt(q.index), {
                        from: '0x3e10889Ef5066C1428ECaf8580aD4EFd50F8Cf7B'
                    }, function(error, result) {
                        console.log('error ' + error);
                        console.log('result ' + result);
                        res.end(result);
                    });
                }
            }
        }
        app.listen(3000, function() {
            console.log('Yep... on 3000 !')
        })
</code>```

i have been trying "res.end(result)" inside and outside of the function 'getData' but the same problem, nothing displayed on the web page

答:
This was a tough nut, but I think I got it.

See here and here and here for how to set headers in Express and how to send data in Express. You are mixing Node's res/req with Express' res/req. Don't do that. Express wraps the Node-objects and works slightly different, e.g. it takes care about the correct headers for you.

This is what you are doing: Using writeHead(), you set the headers. Then, you use .end() with the wrong argument-type: res.end() will only accept strings or Buffers as data (first error). When you change to .send(), that method takes care of setting the correct headers, but you had already done that manually, so you set the headers twice and you should not do that so boom (second error).

Solution is to remove this:

```<code>res.writeHead(200, {
    'Content-Type': 'text/html'
});
</code>```

... and then use res.send(result) to send your data.

As a side note, I would love to know how you are running your app and not getting error logs, because they were all over the place when I tried to build a verifiable example. Verbose error logs are sometimes worth more than the code that created them. This is one of those "sometimes".

Body:
Calling res.end(result) doesn't display the result on my web page, it is just displayed on the console when I call console.log('result ' + result).

this is my nodejs code:

 const express = require('express')
    const app = express()
    var url = require('url');
    var Web3 = require('web3');

app.get('/', function(req, res) {
            res.writeHead(200, {
                'Content-Type': 'text/html'
            });

            if (typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider);
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://54.00.00.00:3010"));
            }

            if (web3.isConnected()) {

                var abi = JSON.parse('[{"constant":true,"inputs":[{"name":"id","type":"uint256"}],"name":"getData","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"uint256"},{"name":"","type":"bytes32"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"Achats","outputs":[{"name":"aName","type":"bytes32"},{"name":"aId","type":"uint256"},{"name":"aDate","type":"bytes32"},{"name":"aValue","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"id","type":"uint256"},{"name":"name","type":"bytes32"},{"name":"iid","type":"uint256"},{"name":"date","type":"bytes32"},{"name":"value","type":"uint256"}],"name":"setData","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]');
                TestContract = web3.eth.contract(abi);
                contractInstance = TestContract.at('0xc08f46fff9fcf082a0d1cebbcc464ca141d2b7d7');

                if (q.opt == 'get' && typeof q.index != "undefined") {
                    contractInstance.getData.call(parseInt(q.index), {
                        from: '0x3e10889Ef5066C1428ECaf8580aD4EFd50F8Cf7B'
                    }, function(error, result) {
                        console.log('error ' + error);
                        console.log('result ' + result);
                        res.end(result);
                    });
                }
            }
        }
        app.listen(3000, function() {
            console.log('Yep... on 3000 !')
        })

i have been trying "res.end(result)" inside and outside of the function 'getData' but the same problem, nothing displayed on the web page

Body:
This was a tough nut, but I think I got it.

See here and here and here for how to set headers in Express and how to send data in Express. You are mixing Node's res/req with Express' res/req. Don't do that. Express wraps the Node-objects and works slightly different, e.g. it takes care about the correct headers for you.

This is what you are doing: Using writeHead(), you set the headers. Then, you use .end() with the wrong argument-type: res.end() will only accept strings or Buffers as data (first error). When you change to .send(), that method takes care of setting the correct headers, but you had already done that manually, so you set the headers twice and you should not do that so boom (second error).

Solution is to remove this:

res.writeHead(200, {
    'Content-Type': 'text/html'
});

... and then use res.send(result) to send your data.

As a side note, I would love to know how you are running your app and not getting error logs, because they were all over the place when I tried to build a verifiable example. Verbose error logs are sometimes worth more than the code that created them. This is one of those "sometimes".


问:
Regexp matching fails with invalid special open parenthesis
I am trying to use regexps in c++11, but my code always throws an std::regex_error of Invalid special open parenthesis.. A minimal example code which tries to find the first duplicate character in a string:

```<code>std::string regexp_string("(?P<a>[a-z])(?P=a)"); // Nothing to be escaped here, right?
std::regex  regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
std::regex_match(target, matched_regexp, regexp_to_match);
for(const auto& m: matched_regexp)
{
    std::cout << m << std::endl;
}
</code>```

Why do I get an error and how do I fix this example?

答: http://en.cppreference.com/w/cpp/regex/ecmascript says that ECMAScript (the default type for std::regex) requires (?= for positive lookahead.

Body:
I am trying to use regexps in c++11, but my code always throws an std::regex_error of Invalid special open parenthesis.. A minimal example code which tries to find the first duplicate character in a string:

std::string regexp_string("(?P[a-z])(?P=a)"); // Nothing to be escaped here, right?
std::regex  regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
std::regex_match(target, matched_regexp, regexp_to_match);
for(const auto& m: matched_regexp)
{
    std::cout << m << std::endl;
}

Why do I get an error and how do I fix this example?


问:
Use pointer to an int as an array index
I have the following code which is a piece of a larger program. I am attempting to pass an int to a function that will copy part of a char array ( name[100] ) to another until a certain character is reached, and update the int value.

```<code>#include <stdio.h>

void time_loop(int *a, char name[100], char *data, char until_char)
{
    int c = 0;
    while(name[*a] != until_char)
    {
        data[c] = name[*a];
        a++;
        c++;
    }
    a = a +  2;
}

int main()
{
    int i = 3;
    char name[100] = {' ', ' ', ' ', 'f', 'o', 'o', ':', '\0'};
    char fill_this[15];

    time_loop(&i, name, fill_this, ':');
    printf("current char index: %d\n", i);
    printf("the word is: %s", fill_this);

    return 0;
}
</code>```

Currently the code runs until it hits the:

```<code>while(name[*a] != until_char)
</code>```

piece of code, with a problem accessing *a.

I could always just take the easy way out and change the function to:

```<code>int time_loop(int a, char name[100], char *data, char until_char)
</code>```

and return an int, but there has to be a way to do this correctly.

Q: What is the correct way to pass a type int* as an index number for an array?

答:
You're not modifying the integer in some cases, you're modifying the pointer to it. For example:

```<code>a++
a = a + 2
</code>```

both do pointer arithmetic - they modify the pointer, not the value pointed to by it. What you want instead is:

```<code>(*a)++
*a += 2
</code>```

These perform the modifications on the value itself, not the pointer.

Note that as you're not doing bounds-checking, you can run over the end of the array (if the character you're searching for isn't in the array), which is undefined behaviour. You should also be sure to null-terminate your output string - add a \0 after the last character. Not doing this can cause undefined behaviour later on if you try to print the string.

Title: Use pointer to an int as an array index

Body:
I have the following code which is a piece of a larger program. I am attempting to pass an int to a function that will copy part of a char array ( name[100] ) to another until a certain character is reached, and update the int value.

#include <stdio.h>

void time_loop(int *a, char name[100], char *data, char until_char)
{
    int c = 0;
    while(name[*a] != until_char)
    {
        data[c] = name[*a];
        a++;
        c++;
    }
    a = a +  2;
}

int main()
{
    int i = 3;
    char name[100] = {' ', ' ', ' ', 'f', 'o', 'o', ':', '\0'};
    char fill_this[15];

    time_loop(&i, name, fill_this, ':');
    printf("current char index: %d\n", i);
    printf("the word is: %s", fill_this);

    return 0;
}

Currently the code runs until it hits the:

while(name[*a] != until_char)

piece of code, with a problem accessing *a.

I could always just take the easy way out and change the function to:

int time_loop(int a, char name[100], char *data, char until_char)

and return an int, but there has to be a way to do this correctly.

Q: What is the correct way to pass a type int* as an index number for an array?

Body:
You're not modifying the integer in some cases, you're modifying the pointer to it. For example:

a++
a = a + 2

both do pointer arithmetic - they modify the pointer, not the value pointed to by it. What you want instead is:

(*a)++
*a += 2

These perform the modifications on the value itself, not the pointer.

Note that as you're not doing bounds-checking, you can run over the end of the array (if the character you're searching for isn't in the array), which is undefined behaviour. You should also be sure to null-terminate your output string - add a \0 after the last character. Not doing this can cause undefined behaviour later on if you try to print the string.


问:
What minimal permission a Global Admin user should have to retrieve data via CSOM API from site collection?
I am trying to get some content from site collections in O365 via CSOM API.

I am using the Global Administrator account and getting the following error:     Access denied. You do not have permission to perform this action or access this resource.

If I give the Global Administrator user that I use the Site Collection Administrator permission, then I am not getting the exception.

Is it possible to give the Global Admin another less powerful then Site Collection Administrator  to achieve the same result?

If no, is there any other API that doesn't require adding the Site Collection Administrator permissions to the Global Administrator?

答: The global administrator should have full access through the whole tenant and shouldn't require you to modify its permissions to access the api. Do you definately mean the global admin account that was used to setup the tenant? Or have you created another account and assigned it global admin access? </p>


问:
Creating and comparing dates inside CosmosDB stored procedures
There is limited guidance for CosmosDB stored procedures and their handling of  new Date() and the comparison of dates.

The following code is a CosmosDB stored procedure to 'freeze' the writing of documents after a given time. The property currentDoc.FreezeDate is in ISO-8601 format, e.g. '2017-11-15T13:34:04Z'.

Note: this is an example of the situation I'm trying to understand. It is not production code.

```<code>function tryUpdate(newDoc) {
  __.queryDocuments(
    __.getSelfLink(),
    { /* query to fetch the document */ },
    (error, results) => {
      var currentDoc = results[0]; // doc from the database
      // fail if the document is still locked
      if (new Date(currentDoc.FreezeDate) < new Date()) {
        getContext().getResponse().setBody({ success: false });
        return;
      }
      // else update the document
      /* snip */
    }
  );
}
</code>```

My question is: within CosmosDB stored procedures, is new Date() affected by timezones, especially given that the database may be in a different region than the invoking code? Is the date comparison code here valid in all situations?

答:
As far as I can see, CosmosDB is storing DateTime values without the corresponding Timezone, aka. not as DateTimeOffset. This means it should not matter where the code is executed, since it is always normalized to something like this:

```<code>  "2014-09-15T23:14:25.7251173Z"
</code>```

Javascript Date object are timestamps - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of to...String methods).

(taken from Parse date without timezone javascript)

In other words, no matter where you are in the world, new Date() will always have the same value internally.

If you want to remove uncertainty in exchange for readability, I would recommend only storing the seconds or milliseconds since the epoch (Unix Time). This is also what is used internally by date (new Date().value - milliseconds). Incidentally, the internal cosmos document field _ts is also a timestamp in epoch format.

Be aware that the value of new Date() might by off the 'correct global time` by a couple of minutes - I don't know if Azure/Cosmos guarantees a certain deviation window.

Body:
There is limited guidance for CosmosDB stored procedures and their handling of  new Date() and the comparison of dates.

The following code is a CosmosDB stored procedure to 'freeze' the writing of documents after a given time. The property currentDoc.FreezeDate is in ISO-8601 format, e.g. '2017-11-15T13:34:04Z'.

Note: this is an example of the situation I'm trying to understand. It is not production code.

function tryUpdate(newDoc) {
  __.queryDocuments(
    __.getSelfLink(),
    { /* query to fetch the document */ },
    (error, results) => {
      var currentDoc = results[0]; // doc from the database
      // fail if the document is still locked
      if (new Date(currentDoc.FreezeDate) < new Date()) {
        getContext().getResponse().setBody({ success: false });
        return;
      }
      // else update the document
      /* snip */
    }
  );
}

My question is: within CosmosDB stored procedures, is new Date() affected by timezones, especially given that the database may be in a different region than the invoking code? Is the date comparison code here valid in all situations?

Body:
As far as I can see, CosmosDB is storing DateTime values without the corresponding Timezone, aka. not as DateTimeOffset. This means it should not matter where the code is executed, since it is always normalized to something like this:

  "2014-09-15T23:14:25.7251173Z"

Javascript Date object are timestamps - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of to...String methods).

(taken from Parse date without timezone javascript)

In other words, no matter where you are in the world, new Date() will always have the same value internally.

If you want to remove uncertainty in exchange for readability, I would recommend only storing the seconds or milliseconds since the epoch (Unix Time). This is also what is used internally by date (new Date().value - milliseconds). Incidentally, the internal cosmos document field _ts is also a timestamp in epoch format.

Be aware that the value of new Date() might by off the 'correct global time` by a couple of minutes - I don't know if Azure/Cosmos guarantees a certain deviation window.


问:
Using Bootstrap Tooltip with AngularJS
I am trying to use the Bootstrap tooltip in an app of mine. My app is using AngularJS Currently, I have the following:

```<code><button type="button" class="btn btn-default"
        data-toggle="tooltip" data-placement="left"
        title="Tooltip on left">
            Tooltip on left
</button>
</code>```

I think I need to use

```<code>$("[data-toggle=tooltip]").tooltip();
</code>```

However, I'm not sure. Even when I add the line above though, my code doesn't work. I'm trying to avoid using UI bootstrap as it has more than I need. However, if I had to include just the tooltip piece, I'd be open to that. Yet, I can't figure out how to do that.

Can someone show me how to get the Bootstrap Tooltip working with AngularJS?

答:
Try the Tooltip (ui.bootstrap.tooltip). See Angular directives for Bootstrap

<button type="button" class="btn btn-default"
tooltip-placement="bottom" uib-tooltip="tooltip message">Test</button>

It is recommended to avoid JavaScript code on the top of AngularJS

Title: Using Bootstrap Tooltip with AngularJS

Body:
I am trying to use the Bootstrap tooltip in an app of mine. My app is using AngularJS Currently, I have the following:

<button type="button" class="btn btn-default"
        data-toggle="tooltip" data-placement="left"
        title="Tooltip on left">
            Tooltip on left
</button>

I think I need to use

$("[data-toggle=tooltip]").tooltip();

However, I'm not sure. Even when I add the line above though, my code doesn't work. I'm trying to avoid using UI bootstrap as it has more than I need. However, if I had to include just the tooltip piece, I'd be open to that. Yet, I can't figure out how to do that.

Can someone show me how to get the Bootstrap Tooltip working with AngularJS?


问:
Python 4.7: How to count the frequency of specific value in array
Basically I have a list with 250 elements, some of them are 1 some 2 and some 3. How do I get a variable that represents the number of ‘1’s ?</p>

答:
This exists natively in Python

```<code>from collections import Counter

A = [1,1,1,1,1,2,2,2,3,3,3,3,3,4,4,4,4]
B = Counter(A)
</code>```

outputs Counter({1: 5, 3: 5, 4: 4, 2: 3})

Body:
This exists natively in Python

from collections import Counter

A = [1,1,1,1,1,2,2,2,3,3,3,3,3,4,4,4,4]
B = Counter(A)

outputs Counter({1: 5, 3: 5, 4: 4, 2: 3})


问:
Angular 2 typescript export value from a class
```<code>import {TranslateService, LangChangeEvent} from "@ngx-translate/core";
class ExportLanguageFun {
    public currentLang : string;
    constructor(private translate : TranslateService) {
    }
    public static setValue(): string {
        this.translate
        .onLangChange
    .subscribe(lang => {
     this.currentLang = lang;
    })
    return this.currentLang;
        }
    }
</code>```

export let exportLanguage = ExportLanguageFun.setValue();
//Error:  Property 'setValue' does not exist on type 'typeof ExportLanguageFun'.

Expected output
console.log(let+"someValue");

答:
You should rethink your structure here. What you want returned here is the lang from inside the observable. You need to restructure what you are doing here.

```<code>public static setValue(): string {
    return this.translate.onLangChange
}
</code>```

Then when you call the function you could subscribe to it and do something with it there.

```<code>this.setValue().subscribe(lang => {
  this.currentLang = lang;
  // do something else with it
})
</code>```

By subscribing, each time there is a new value, the function will run. Instead of trying to return the value just do something with it with each change, wherever you subscribe to it.

Body:
import {TranslateService, LangChangeEvent} from "@ngx-translate/core";
class ExportLanguageFun {
    public currentLang : string;
    constructor(private translate : TranslateService) {
    }
    public static setValue(): string {
        this.translate
        .onLangChange
    .subscribe(lang => {
     this.currentLang = lang;
    })
    return this.currentLang;
        }
    }

export let exportLanguage = ExportLanguageFun.setValue();
//Error:  Property 'setValue' does not exist on type 'typeof ExportLanguageFun'.

Expected output
console.log(let+"someValue");

Body:
You should rethink your structure here. What you want returned here is the lang from inside the observable. You need to restructure what you are doing here.

public static setValue(): string {
    return this.translate.onLangChange
}

Then when you call the function you could subscribe to it and do something with it there.

this.setValue().subscribe(lang => {
  this.currentLang = lang;
  // do something else with it
})

By subscribing, each time there is a new value, the function will run. Instead of trying to return the value just do something with it with each change, wherever you subscribe to it.


问:
Send ForeignKey Column value in kendo grid to controller on inline edit
I have been struggling with this for quite sometime. I have a kendo grid which has several dropdownlists inside the grid. I put dropdownlist in the grid using the foreign key column. The grid on inline edit doesn't send the selected dropdownlist value to the controller, it sends the old value. I'm not quite sure what's going wrong, any leads will be very helpful.

Code:

View

```<code>     @(Html.Kendo().Grid(Model.App_Client_Mapping)
    .Name("AppAccountInternalGrid")
    .Events(ev => ev.Edit("OnGridEdit"))
    .Columns(columns =>
    {

        columns.Bound(p => p.AccountMappingID).Title("AccountMappingID").Width(130).Hidden(true);

        columns.ForeignKey(p => p.Level1ID, (System.Collections.IEnumerable)ViewData["level1"], "Level1ID", "Level1").Title("Level 1").Width(150).HtmlAttributes(new { id = "Level1Dropdown", data_value_primitive = true });

        columns.ForeignKey(p => p.Level2ID, (System.Collections.IEnumerable)ViewData["level2"], "Level2ID", "Level2").Title("Level 2").Width(150).HtmlAttributes(new { id = "Level2Dropdown" });

        columns.Bound(p => p.ExternalAccount).Title("ExternalAccount").Width(150);
})

         .Editable(editable => editable.Mode(GridEditMode.InLine))
         .DataSource(dataSource => dataSource
             .Ajax()
             .PageSize(50)
             .Model(model =>
            {
                model.Id(p => p.AccountMappingID);
                model.Field(p => p.AccountMappingID).Editable(false);
                model.Field(p => p.Level1ID).DefaultValue(1).Editable(true);
                model.Field(p => p.Level1).Editable(true);
                model.Field(p => p.Level2ID).DefaultValue(0).Editable(true);
                model.Field(p => p.Level2).Editable(true);
            }

            )

          .Update("EditingInline_Update", "AppAccounts")
          .ServerOperation(false)
     )

                )
</code>```

Controller:

The grid gets data from this action. The view has other elements along with the grid, so i binded a view model.

```<code> public ActionResult AppInternal(int clientid)
    {
     var result = new AppViewModel();

    result.App_Client_Mapping=_unitofwork.AppInternal.Get(clientid);

        var level1 = level1list.Select(x => new App_Client_Mapping
                {

                    Level1ID = x.LevelID,
                    Level1 = x.Level1
                }).ToList();

     var level2 = level2list.Select(x => new App_Client_Mapping
                {

                    Level2ID = x.Level2ID,
                    Level2 = x.Level2

                }).ToList();

          ViewData["level1"] = level1;

                ViewData["level2"] = level2;

    }
     [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult EditingInline_Update([DataSourceRequest] DataSourceRequest request, App_Client_Mapping mapping)
        {
           //save the mapping in the database tables

                    return Json(new[] { mapping }.ToDataSourceResult(request, ModelState));
    }
</code>```

ViewModel:

AppViewModel:

```<code>  public class AppMappingViewModel
{
public IEnumerable<App_Client_Mapping> App_Client_Mapping { get; set; }

//other fields

}
</code>```

Auto-generated app_client_mapping class from EF:

```<code>    public class app_client_mapping
    {
    public int AccountMappingID{get;set;}
    public int Level1ID{get;set;}
    public string Level1{get;set;}
    public int Level2ID{get;set;}
    public string Level2{get;set;}
   public string ExternalAccount{get;set;}
    }
</code>```

When the dataset is passed to the controller. Only the updated value of external local amount (which is a textbox) in the grid is sent. The updated dropdown values aren't sent to the grid. Any ideas as to why this is happening will be a huge help.

Thanks!

答:
You seem to be missing the .Read action for your grid ?

Here is how I have my dropdowns inside my grid. I have tried to make it as much a like to your code.

Controller:

```<code>public IActionResult AppInternal()
{
  ViewData["level1"] = _context.level1list.Select(x => new App_Client_Mapping {
                Level1ID = x.LevelID,
                Level1 = x.Level1
            }); // Do not return a .List()
  // put more dropdowns as required...
  return View();
}

// return the .Read action from your grid
public IActionResult Read([DataSourceRequest] DataSourceRequest request)
{
  var result = new AppViewModel();
  result.App_Client_Mapping=_unitofwork.AppInternal.Get(clientid);
  return Json(result.ToDataSourceResult(request));
}

// Update
public EditingInline_Update([DataSourceRequest] DataSourceRequest request, App_Client_Mapping mapping)
{
    if (ModelState.IsValid)
    {
        // update db with the Level1ID from your dropdown
    }
    // Return the updated product. Also return any validation errors.
    return Json(new[] { mapping }.ToDataSourceResult(request, ModelState));
}
</code>```

View:

```<code>columns.ForeignKey(p => p.Level1ID, (System.Collections.IEnumerable)ViewData["level1"], "Level1ID", "Level1").Title("Level 1").Width(150); // Don't need to put HtmlAttributes.

// The .Read Action should be
.Read(read => read.Action("Read", "AppAccounts")
</code>```

Foreign Key EditorTemplate:

```<code>@model object

@(Html.Kendo().ComboBoxFor(m => m)
    .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
    .ValuePrimitive(true)
)
</code>```

There is some code example here: MVC Demo

Body:
I have been struggling with this for quite sometime. I have a kendo grid which has several dropdownlists inside the grid. I put dropdownlist in the grid using the foreign key column. The grid on inline edit doesn't send the selected dropdownlist value to the controller, it sends the old value. I'm not quite sure what's going wrong, any leads will be very helpful.

Code:

View

     @(Html.Kendo().Grid(Model.App_Client_Mapping)
    .Name("AppAccountInternalGrid")
    .Events(ev => ev.Edit("OnGridEdit"))
    .Columns(columns =>
    {

        columns.Bound(p => p.AccountMappingID).Title("AccountMappingID").Width(130).Hidden(true);

        columns.ForeignKey(p => p.Level1ID, (System.Collections.IEnumerable)ViewData["level1"], "Level1ID", "Level1").Title("Level 1").Width(150).HtmlAttributes(new { id = "Level1Dropdown", data_value_primitive = true });

        columns.ForeignKey(p => p.Level2ID, (System.Collections.IEnumerable)ViewData["level2"], "Level2ID", "Level2").Title("Level 2").Width(150).HtmlAttributes(new { id = "Level2Dropdown" });

        columns.Bound(p => p.ExternalAccount).Title("ExternalAccount").Width(150);
})

         .Editable(editable => editable.Mode(GridEditMode.InLine))
         .DataSource(dataSource => dataSource
             .Ajax()
             .PageSize(50)
             .Model(model =>
            {
                model.Id(p => p.AccountMappingID);
                model.Field(p => p.AccountMappingID).Editable(false);
                model.Field(p => p.Level1ID).DefaultValue(1).Editable(true);
                model.Field(p => p.Level1).Editable(true);
                model.Field(p => p.Level2ID).DefaultValue(0).Editable(true);
                model.Field(p => p.Level2).Editable(true);
            }

            )

          .Update("EditingInline_Update", "AppAccounts")
          .ServerOperation(false)
     )

                )

Controller:

The grid gets data from this action. The view has other elements along with the grid, so i binded a view model.

 public ActionResult AppInternal(int clientid)
    {
     var result = new AppViewModel();

    result.App_Client_Mapping=_unitofwork.AppInternal.Get(clientid);

        var level1 = level1list.Select(x => new App_Client_Mapping
                {

                    Level1ID = x.LevelID,
                    Level1 = x.Level1
                }).ToList();

     var level2 = level2list.Select(x => new App_Client_Mapping
                {

                    Level2ID = x.Level2ID,
                    Level2 = x.Level2

                }).ToList();

          ViewData["level1"] = level1;

                ViewData["level2"] = level2;

    }
     [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult EditingInline_Update([DataSourceRequest] DataSourceRequest request, App_Client_Mapping mapping)
        {
           //save the mapping in the database tables

                    return Json(new[] { mapping }.ToDataSourceResult(request, ModelState));
    }

ViewModel:

AppViewModel:

  public class AppMappingViewModel
{
public IEnumerable<App_Client_Mapping> App_Client_Mapping { get; set; }

//other fields

}

Auto-generated app_client_mapping class from EF:

    public class app_client_mapping
    {
    public int AccountMappingID{get;set;}
    public int Level1ID{get;set;}
    public string Level1{get;set;}
    public int Level2ID{get;set;}
    public string Level2{get;set;}
   public string ExternalAccount{get;set;}
    }

When the dataset is passed to the controller. Only the updated value of external local amount (which is a textbox) in the grid is sent. The updated dropdown values aren't sent to the grid. Any ideas as to why this is happening will be a huge help.

Thanks!

Body:
You seem to be missing the .Read action for your grid ?

Here is how I have my dropdowns inside my grid. I have tried to make it as much a like to your code.

Controller:

public IActionResult AppInternal()
{
  ViewData["level1"] = _context.level1list.Select(x => new App_Client_Mapping {
                Level1ID = x.LevelID,
                Level1 = x.Level1
            }); // Do not return a .List()
  // put more dropdowns as required...
  return View();
}

// return the .Read action from your grid
public IActionResult Read([DataSourceRequest] DataSourceRequest request)
{
  var result = new AppViewModel();
  result.App_Client_Mapping=_unitofwork.AppInternal.Get(clientid);
  return Json(result.ToDataSourceResult(request));
}

// Update
public EditingInline_Update([DataSourceRequest] DataSourceRequest request, App_Client_Mapping mapping)
{
    if (ModelState.IsValid)
    {
        // update db with the Level1ID from your dropdown
    }
    // Return the updated product. Also return any validation errors.
    return Json(new[] { mapping }.ToDataSourceResult(request, ModelState));
}

View:

columns.ForeignKey(p => p.Level1ID, (System.Collections.IEnumerable)ViewData["level1"], "Level1ID", "Level1").Title("Level 1").Width(150); // Don't need to put HtmlAttributes.

// The .Read Action should be
.Read(read => read.Action("Read", "AppAccounts")

Foreign Key EditorTemplate:

@model object

@(Html.Kendo().ComboBoxFor(m => m)
    .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
    .ValuePrimitive(true)
)

There is some code example here: MVC Demo


问:
Azure Search Instead of Elasticsearch
The existing application is running in elasticsearch. The functionality of the application covers.

MLT search

synonym search

stopwords

multilingual search

Filtered search

kibana dashboard uses aggregations to show the metrics in the dashboard.

Is it possible to achieve all these functionality in azure-search ?

答: Azure Search doesn't integrate with Kibana and doesn't support aggregations. All the other functionalities you mentioned are supported in Azure Search. Hope that helps.</p>

Title: Azure Search Instead of Elasticsearch


问:
C++: Calling sendmail from pthread results in Broken Pipe
I'm trying to send an e-mail with sendmail in a separate pthread.  This code works 99.9% of the time.

```<code>void* emailClientThreadFct(void* emailClientPtr)
{
   EmailClient* emailClient = static_cast<EmailClient*>(emailClientPtr);

   try
   {
      emailClient->Send();
   }
   catch (const exception& excep)
   {
      SYSLOG_ERROR("E-mail client exception: %s", excep.what());
   }

   delete emailClient;
   return NULL;
}

// Send email for current output in a separate thread
pthread_t emailThread;
pthread_attr_t attr;

/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

pthread_create(&emailThread, &attr, emailClientThreadFct, emailClientObj);
</code>```

0.1% of the time, I get the error fwrite error Broken Pipe when I do the following call.  From what I read, Broken Pipe (EPIPE 32) is usually a receiver problem, but sendmail is a local process... Could it be that I'm sending too much data to fwrite?  Or that I'm doing something bad in my pthread instanciation?  Or has sendmail crashed?

```<code>void EmailClient::Send() const
{
   // Flush all open output streams, as recommended by popen man page
   fflush(NULL);

   string popen_command = "sendmail -t -oi >/dev/null 2>&1");

   // Open pipe to Mail Transport Agent (MTA)
   errno = 0;
   FILE* stream = popen(popen_command.c_str(), "w");

   if (stream == NULL)
   {
      throw exception("Cannot send email popen");
   }
   errno = 0;
   if (fwrite(message.data(), message.size(), 1, stream) < 1)
   {
      pclose(stream);
      throw exception("fwrite error ", strerror(errno));
   }

   // Close MTA
   errno = 0;
   if (pclose(stream) == -1)
      printf("\"Error closing the MTA pipe (%s)\"", strerror(errno))
}
</code>```

答:
EPIPE means that the other end (the process you are writing to) has died.  This could happen if there is a fork failure (popen invokes the shell, so there is another subprocess involved) because there are temporarily too many processes in the system.  A more direct cause would be sendmail failing and exiting prematurely, before reading all of standard input, say due to malformed email headers.

popen is unfortunately not a very reliable interface.  You might be better off using fork/execve or posix_spawn, either with a temporary file for the input or I/O multiplexing using poll, just to be able to capture any error that sendmail might generate.  Alternatively, you could try to call sendmail with -oee, which is supposed to report any errors by email, but it won't help if the creation of the sendmail itself fails.

Body:
I'm trying to send an e-mail with sendmail in a separate pthread.  This code works 99.9% of the time.

void* emailClientThreadFct(void* emailClientPtr)
{
   EmailClient* emailClient = static_cast<EmailClient*>(emailClientPtr);

   try
   {
      emailClient->Send();
   }
   catch (const exception& excep)
   {
      SYSLOG_ERROR("E-mail client exception: %s", excep.what());
   }

   delete emailClient;
   return NULL;
}

// Send email for current output in a separate thread
pthread_t emailThread;
pthread_attr_t attr;

/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

pthread_create(&emailThread, &attr, emailClientThreadFct, emailClientObj);

0.1% of the time, I get the error fwrite error Broken Pipe when I do the following call.  From what I read, Broken Pipe (EPIPE 32) is usually a receiver problem, but sendmail is a local process... Could it be that I'm sending too much data to fwrite?  Or that I'm doing something bad in my pthread instanciation?  Or has sendmail crashed?

void EmailClient::Send() const
{
   // Flush all open output streams, as recommended by popen man page
   fflush(NULL);

   string popen_command = "sendmail -t -oi >/dev/null 2>&1");

   // Open pipe to Mail Transport Agent (MTA)
   errno = 0;
   FILE* stream = popen(popen_command.c_str(), "w");

   if (stream == NULL)
   {
      throw exception("Cannot send email popen");
   }
   errno = 0;
   if (fwrite(message.data(), message.size(), 1, stream) < 1)
   {
      pclose(stream);
      throw exception("fwrite error ", strerror(errno));
   }

   // Close MTA
   errno = 0;
   if (pclose(stream) == -1)
      printf("\"Error closing the MTA pipe (%s)\"", strerror(errno))
}


问:
C# WPF Binding path not working
I currently have a ListBox that is bound to a collection of objects and displays a button for each object in the collection.

XAML:

```<code><Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>

    <ListBox x:Name="company_buttons"
             HorizontalContentAlignment="Left" VerticalContentAlignment="Top"
             Padding="-2,-2,0,0" Height="280" Width="300" Background="{x:Null}" BorderBrush="{x:Null}" Margin="0,0,0,0" BorderThickness="0"
             ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
             ItemsSource="{Binding Buttons_Binding}">

        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>

                    <Button Background="#FFFCC515" Style="{StaticResource RoundCorner}" FontFamily="Segoe UI" FontSize="16" FontWeight="Bold" TabIndex="0"
                                CommandParameter="{Binding This_Works}"
                                Command="{Binding HELP WITH THIS}">
                        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Width="270" Height="44">
                            <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Top" Margin="5,0,5,0" Height="21" Padding="0" Content="{Binding This_Works}"/>
                            <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Top" Margin="5,0,5,0" Height="21" Padding="0" Content="{Binding This_Works}"/>
                        </StackPanel>
                    </Button>

                    <Label VerticalContentAlignment="Top" Margin="5,0,5,0" Height="19" Padding="0" Foreground="White" FontFamily="Segoe UI" FontSize="12" FontWeight="Bold" Content="{Binding Path}"/>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>
</code>```

Here are the things that are used in the bindings:

```<code>public class ButtonContent : INotifyPropertyChanged
{
 // stuff
}

public class MainWindowViewModel
{
    public static ObservableCollection<ButtonContent> Buttons_Binding
    {
 // stuff
    }

    public ICommand Command
    {
 // stuff
    }
</code>```

My problem is I do not know how to bind the button click to Command since it is outside of the collection Buttons_Binding and hence not in the same data context. All the stuff I have seen from examples and what I have tried have all failed.

答:
Since each Button is bound to the ListBoxItem's DataContext, it will not have access to the ListBox's DataContext. However, you can traverse the visual tree using RelativeSource in the binding. Try this </p>

```<code><Button ...
        Command="{Binding Path=DataContext.Command,
                  RelativeSource={RelativeSource AncestorType=ListBox}}">
    ...
</Button>
</code>```

Title: C# WPF Binding path not working

Body:
I currently have a ListBox that is bound to a collection of objects and displays a button for each object in the collection.

XAML:

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>

    <ListBox x:Name="company_buttons"
             HorizontalContentAlignment="Left" VerticalContentAlignment="Top"
             Padding="-2,-2,0,0" Height="280" Width="300" Background="{x:Null}" BorderBrush="{x:Null}" Margin="0,0,0,0" BorderThickness="0"
             ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
             ItemsSource="{Binding Buttons_Binding}">

        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>

                    <Button Background="#FFFCC515" Style="{StaticResource RoundCorner}" FontFamily="Segoe UI" FontSize="16" FontWeight="Bold" TabIndex="0"
                                CommandParameter="{Binding This_Works}"
                                Command="{Binding HELP WITH THIS}">
                        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Width="270" Height="44">

                        </StackPanel>
                    </Button>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>

Here are the things that are used in the bindings:

public class ButtonContent : INotifyPropertyChanged
{
 // stuff
}

public class MainWindowViewModel
{
    public static ObservableCollection<ButtonContent> Buttons_Binding
    {
 // stuff
    }

    public ICommand Command
    {
 // stuff
    }

My problem is I do not know how to bind the button click to Command since it is outside of the collection Buttons_Binding and hence not in the same data context. All the stuff I have seen from examples and what I have tried have all failed.

Body:
Since each Button is bound to the ListBoxItem's DataContext, it will not have access to the ListBox's DataContext. However, you can traverse the visual tree using RelativeSource in the binding. Try this

<Button ...
        Command="{Binding Path=DataContext.Command,
                  RelativeSource={RelativeSource AncestorType=ListBox}}">
    ...
</Button>


问:
Android Runtime Exception font asset not found
Here is my code and screenshot I'm trying to set custom font typeface but Runtime exception occurs font asset not found while font file is in asset folder. Am I missing something ?

```<code>Typeface font = Typeface.createFromAsset(getAssets(), "font/terminal.ttf");
((TextView) findViewById(R.id.weatherHeadingTV)).setTypeface(font);
</code>```

答: For me, the font file itself was corrupted. I tried another one to make it work. </p>

Body:
Here is my code and screenshot I'm trying to set custom font typeface but Runtime exception occurs font asset not found while font file is in asset folder. Am I missing something ?

Typeface font = Typeface.createFromAsset(getAssets(), "font/terminal.ttf");
((TextView) findViewById(R.id.weatherHeadingTV)).setTypeface(font);


问:
Java: upload file to FTP problem (packets lost)
I'm trying to transfer a file from my Java application to an FTP server
the program works, the file is transferred, but when I go to open in the FTO folder, the file is corrupted, I think that packets are lost during the file transfer.  Why?  And how can I fix this?

Another question, how can I stop the while if I want to stop the file upload?

Thanks everybody!

The code inside my class:

```<code>FTPClient client = new FTPClient();
InputStream is = null;
//...
try{
 client.connect(MY_FTP_URL);
 client.login(USER, PASS);
 InputStream is = new FileInputStream(file_path);
 OutputStream os = client.storeFileStream(file_name);
 byte[] buffer = new byte[1024];
 int len;
 //I use this way to check the transfer progress
 while((len = is.read(buffer)) != -1){
  os.write(buffer, 0, len);
  os.flush();
 }
 os.close();
} catch (IOException e){
 e.printStackTrace();
} finally{
 try{
  if(is != null){
   is.close();
  }
  client.disconnect();
 } catch(IOException e){
  e.printStackTrace();
 }
}
</code>```

答:
FTP has two modes ASCII (typically the default) and binary. If you are transferring anything other then text you must set the client into binary mode.

How to set the mode varies on the FTP client implementation, but for Commons IO see
http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html#setFileType(int)

Body:
I'm trying to transfer a file from my Java application to an FTP server
the program works, the file is transferred, but when I go to open in the FTO folder, the file is corrupted, I think that packets are lost during the file transfer.  Why?  And how can I fix this?

Another question, how can I stop the while if I want to stop the file upload?

Thanks everybody!

The code inside my class:

FTPClient client = new FTPClient();
InputStream is = null;
//...
try{
 client.connect(MY_FTP_URL);
 client.login(USER, PASS);
 InputStream is = new FileInputStream(file_path);
 OutputStream os = client.storeFileStream(file_name);
 byte[] buffer = new byte[1024];
 int len;
 //I use this way to check the transfer progress
 while((len = is.read(buffer)) != -1){
  os.write(buffer, 0, len);
  os.flush();
 }
 os.close();
} catch (IOException e){
 e.printStackTrace();
} finally{
 try{
  if(is != null){
   is.close();
  }
  client.disconnect();
 } catch(IOException e){
  e.printStackTrace();
 }
}


问:
Django: Read uploaded CSV file using FileField instance
I'm trying to read the data of a .csv file uploaded by a user in a field of type FileField. I have no problem acessing the object, but I can't seem to make it work with the csv module. Here is what I'm trying:

```<code>reader = csv.reader(object.uploaded_file.read())
for rows in reader:
...
</code>```

Where object is an instance of my model and uploaded_file the corresponding field.

I'm getting this error:

iterator should return strings, not int (did you open the file in text
  mode?)

Also,

I tried to use the open() method but whitout success. The documentation on this subject seems so vague. Even worst, the only thing I could find on the read() method used above is this:

In addition to the listed methods, File exposes the following
  attributes and methods of its file object: encoding, fileno, flush,
  isatty, newlines, read, readinto, readline, readlines, seek,
  softspace, tell, truncate, write, writelines, xreadlines, readable(),
  writable(), and seekable().

EDIT

I know it probably has to do with the reading mode has this thread suggest, but how can I change the mode in this case ?

答:
I finally found a work around:

```<code> reader = csv.reader(open(object.uploaded_file.path,'r'))
</code>```

Instead of using built-in read() or open() of File object which has low documentation as I said in my question, I used the path attribute.

Body:
I'm trying to read the data of a .csv file uploaded by a user in a field of type FileField. I have no problem acessing the object, but I can't seem to make it work with the csv module. Here is what I'm trying:

reader = csv.reader(object.uploaded_file.read())
for rows in reader:
...

Where object is an instance of my model and uploaded_file the corresponding field.

I'm getting this error:

iterator should return strings, not int (did you open the file in text
  mode?)

Also,

I tried to use the open() method but whitout success. The documentation on this subject seems so vague. Even worst, the only thing I could find on the read() method used above is this:

In addition to the listed methods, File exposes the following
  attributes and methods of its file object: encoding, fileno, flush,
  isatty, newlines, read, readinto, readline, readlines, seek,
  softspace, tell, truncate, write, writelines, xreadlines, readable(),
  writable(), and seekable().

EDIT

I know it probably has to do with the reading mode has this thread suggest, but how can I change the mode in this case ?

Body:
I finally found a work around:

 reader = csv.reader(open(object.uploaded_file.path,'r'))

Instead of using built-in read() or open() of File object which has low documentation as I said in my question, I used the path attribute.