问:
Vue syntax error
I am trying to print out the name property of an object using Vue.

Here's what I tried {{ selectedTopic.name }}, this throws this error Uncaught TypeError: Cannot read property 'name' of null

If I print out {{ selectedTopic }} it will wait until that data is available and then display without errors.

Now I understand that the data I'm requesting is not available at that stage, but why is it throwing an error? Shouldn't it just wait until that data becomes available like it does for {{ selectedTopic }}?

Vue app

```<code>  var qaSuggest = new Vue({
    el: '#qa-suggest',
    data: {
      selectedTopic: null,
      profiles: []
    },
    mounted() {
      bus.$on("send-topic", selectedTopic => this.selectedTopic = selectedTopic);
    },
    updated(){
      axios.get('/vueprofiles').then(response => this.profiles = response.data);
      console.log('selectedTopic: ', this.selectedTopic.name);
    }
  });
</code>```

HTML

```<code><div id="qa-suggest">
    <ul class="list-unstyled">
        <li v-for="profile in profiles">
          <div class="clearfix" style="border-bottom: 1px solid #ddd; padding: 5px;">
        <div class="pull-left">
          <img :src="profile.picture" class="img-responsive" style="max-width: 60px; margin-right: 10px;">
        </div>
        <div class="pull-left">
          <p style="font-size: 12px; margin-bottom: 0;">{{ profile.category }} / {{ profile.subcategory }}</p>
          <p><strong>{{ profile.name }}</strong></p>
        </div>
      </div>
    </li>
</ul>

Topic: {{ selectedTopic.name }}
</code>```

答:
The error is because you can't access a property on an object that is null. Instead, you might try</p>

```<code>{{ selectedTopic ? selectedTopic.name : '' }}
</code>```

Title: Vue syntax error

Body:
I am trying to print out the name property of an object using Vue.

Here's what I tried {{ selectedTopic.name }}, this throws this error Uncaught TypeError: Cannot read property 'name' of null

If I print out {{ selectedTopic }} it will wait until that data is available and then display without errors.

Now I understand that the data I'm requesting is not available at that stage, but why is it throwing an error? Shouldn't it just wait until that data becomes available like it does for {{ selectedTopic }}?

Vue app

  var qaSuggest = new Vue({
    el: '#qa-suggest',
    data: {
      selectedTopic: null,
      profiles: []
    },
    mounted() {
      bus.$on("send-topic", selectedTopic => this.selectedTopic = selectedTopic);
    },
    updated(){
      axios.get('/vueprofiles').then(response => this.profiles = response.data);
      console.log('selectedTopic: ', this.selectedTopic.name);
    }
  });

HTML

{{ profile.category }} / {{ profile.subcategory }}

{{ profile.name }}

Topic: {{ selectedTopic.name }}

Body:
The error is because you can't access a property on an object that is null. Instead, you might try

{{ selectedTopic ? selectedTopic.name : '' }}


来源: stackexchange

问:
C# GUI Programming Starting
So....I've never really done much in the way of GUI programming apps. Namely because for school ive been stuck in C++ land. But since Im graduating in December I thought it'd be nice (while im looking for a job) to study something I've wanted to look into for awhile. And please dont mark this as "subjective" im just simply asking what I need to "know" to get started.

Namely GUI programming. Im not used to it....nor have I really ever been. It's not something they focus on in school (for instance my senior design was a webcam mouse thing, but had very little in the way of GUI)

I've seen alot about C# being the superior GUI programming tool for fast development.....but I dont really know whats out there. I know "of" QT, and Im used to C++. However Im not too familiar with what the "choice" GUI language is. I do like programming on Windows however most of my stuff has been in Unix here lately (Mostly because of my OS class).

I dont know anything about .net, and i've heard of something called WPF? Is that part of .net.....or.....what? Im just a bit confused at where to start.

Thanks

答:
You have two choices to go with:

Windows Forms (WinForms)
Windows Presentation Foundation (WPF)

For all future desktop GUI applications, WPF is recommended.

ContentLicense: CC BY-SA 2.5

Title: C# GUI Programming Starting


答:
It doesn't "wait" so much as understand that undefined should be an empty string. You could initialize selectedTopic with an empty object, and you would get the result you're looking for.

```<code>data: {
  selectedTopic: {},
  profiles: []
},
</code>```

ContentLicense: CC BY-SA 3.0

Title: Vue syntax error

Body:
It doesn't "wait" so much as understand that undefined should be an empty string. You could initialize selectedTopic with an empty object, and you would get the result you're looking for.

data: {
  selectedTopic: {},
  profiles: []
},


问:
Label wrapping with StackLayout
I'm using Xamarin and creating my view with XAML and I cannot for the life of me get this label to wrap the way I want it to. If the label gets to the edge of the screen, I want it to wrap like this...

Right now it is looking like this...

Here is my code:

```<code><StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand" BindingContext="{Binding CurrentProviderDetails}" Padding="20,20,20,20" >
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
<!--Certification Board-->
  <StackLayout Orientation="Horizontal" HorizontalOptions="StartAndExpand" Grid.Row="0" Grid.Column="0" >
    <Label Text="Certification Board: " FontSize="13" HorizontalOptions="Fill" VerticalOptions="CenterAndExpand" />
    <Label Text="{Binding Certification}" VerticalOptions="CenterAndExpand"  HorizontalOptions="Center" Font="17" LineBreakMode="WordWrap"/>
  </StackLayout>
 </Grid>
</StackLayout>
</code>```

This doesn't need to be in a grid; this was just the method I was trying for now. My only requirement is that 'Certification Board' is a label, and I have to pass in a value that word wraps when it gets to the end of the screen. Any help would be awesome, Thanks!

答:
You can achieve the desired look by combining both of the Labels contained in your horizontally aligned StackLayout into a single Label and setting LineBreakMode="WordWrap".  XAML has a great feature known as StringFormat.  You can use this to prepend the static "Certification Board:" text to the bound Certification property.
Your Label should look like this:</p>

```<code><Label Text="{Binding Certification, StringFormat='Board Certification:{0:F0}'}" LineBreakMode="WordWrap"/>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Label wrapping with StackLayout

Body:
I'm using Xamarin and creating my view with XAML and I cannot for the life of me get this label to wrap the way I want it to. If the label gets to the edge of the screen, I want it to wrap like this...

Right now it is looking like this...

Here is my code:

<StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand" BindingContext="{Binding CurrentProviderDetails}" Padding="20,20,20,20" >
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>

  <StackLayout Orientation="Horizontal" HorizontalOptions="StartAndExpand" Grid.Row="0" Grid.Column="0" >

  </StackLayout>
 </Grid>
</StackLayout>

This doesn't need to be in a grid; this was just the method I was trying for now. My only requirement is that 'Certification Board' is a label, and I have to pass in a value that word wraps when it gets to the end of the screen. Any help would be awesome, Thanks!

Body:
You can achieve the desired look by combining both of the Labels contained in your horizontally aligned StackLayout into a single Label and setting LineBreakMode="WordWrap".  XAML has a great feature known as StringFormat.  You can use this to prepend the static "Certification Board:" text to the bound Certification property.
Your Label should look like this:

<Label Text="{Binding Certification, StringFormat='Board Certification:{0:F0}'}" LineBreakMode="WordWrap"/>


问:
How to install Mono on macOS so mono works in terminal?
I'm trying to get a Mono install running on a mac (OS X version 10.10.5), and while the install states that it's completed successfully, I'm not able to call mono from the terminal.

To install it, I ran uninstallMono.sh as root to ensure we didn't have any leftover cruft, then ran MonoFramework-MDK-4.0.4.1.macos10.xamarin.x86.pkg. The installer appeared to complete successfully, but an attempt to call mono returns

-bash: mono: command not found

The mono framework does appear to be installed:

```<code>Lees-Mac-Pro:Downloads kevinmack$ cd /Volumes/Macintosh\ HD/Library/Frameworks/
Lees-Mac-Pro:Frameworks kevinmack$ ls -l
total 32
lrwxr-xr-x  1 root  wheel   71 Jan 20  2015 AEProfiling.framework -> ../../Applications/Motion.app/Contents/Frameworks/AEProfiling.framework
lrwxr-xr-x  1 root  wheel   74 Jan 20  2015 AERegistration.framework -> ../../Applications/Motion.app/Contents/Frameworks/AERegistration.framework
lrwxr-xr-x  1 root  wheel   74 Jan 20  2015 AudioMixEngine.framework -> ../../Applications/Motion.app/Contents/Frameworks/AudioMixEngine.framework
drwxr-xr-x  8 root  admin  272 Sep 12 11:24 Mono.framework
lrwxr-xr-x  1 root  wheel   60 Sep  9 22:16 NyxAudioAnalysis.framework -> /System/Library/PrivateFrameworks/NyxAudioAnalysis.framework
drwxr-xr-x  5 root  wheel  170 Jan 20  2015 PluginManager.framework
drwxr-xr-x  8 root  wheel  272 Sep  9 22:19 iTunesLibrary.framework
</code>```

...but it isn't present in /usr/bin and attempting to find its executable using which mono returns nothing.

答:
Quick Summary:
Atm, the mono framework installer only works correctly if you install it to root.  It will automatically add /Library/Frameworks/Mono.framework/Versions/Current/Commands to $PATH, but I don't know if you will need to add /Library/Frameworks/Mono.framework/Versions/Current/bin/ by hand or if everything just works. (Commands is a symbolic link to bin, but it still may not work)

More in-depth:
I recently installed mono from MonoFramework-MDK-4.8.0.520.macos10.xamarin.universal.pkg.  I installed it to /Volumes/osxapps/ instead of root, but the installation still expected everything to be in root.  It added /Library/Frameworks/Mono.framework/Versions/Current/Commands to $PATH but everything in /Library/Frameworks/Mono.framework/ was just empty directories.  All the files resided in /Volumes/osxapps/Library/Frameworks/Mono.framework/.

Furthermore, a lot of what was in /Volumes/osxapps/Library/Frameworks/Mono.framework/ including Commands were not folders but symbolic links that didn't work because they expected the folders to be in root.  For example: If everything were installed in root,
/Library/Frameworks/Mono.framework/Versions/Current/Commands is a symlink to /Library/Frameworks/Mono.framework/Versions/Current/bin and /Library/Frameworks/Mono.framework/Versions/Current/ is also a symlink.

I added:

```<code>export PATH="/Volumes/osxapps/Library/Frameworks/Mono.framework/Versions/4.8.0/bin:$PATH"
</code>```

to .bash_profile, in ~/, which allowed me to run the commands/executables, but they all died with errors because they were still expecting things to be in root.

So I copied the folder from /Volumes/osxapps/Library/Frameworks to /Library/Frameworks/ and that solved all the errors and things are working properly but now I have two copies of Mono.framework and I didn't want it installed in root in the first place, because root is on an ssd, and space is limited.

A better solution would be to uninstall mono according to the instructions at bottom of this page and then reinstall on root.

However, it would still be better, for me, to install on /Volumes/osxapps/, but I don't know the best way to go about doing that.  (I could probably just recreate a bunch of symbolic links).  I was going to tell the mono-project that their installer mucks everything up if you don't install to root, but I'm not sure the best way to go about doing that either.  So, instead I have posted here, with what I have learned so far, in the hope that it could help someone else.

Body:
I'm trying to get a Mono install running on a mac (OS X version 10.10.5), and while the install states that it's completed successfully, I'm not able to call mono from the terminal.

To install it, I ran uninstallMono.sh as root to ensure we didn't have any leftover cruft, then ran MonoFramework-MDK-4.0.4.1.macos10.xamarin.x86.pkg. The installer appeared to complete successfully, but an attempt to call mono returns

-bash: mono: command not found

The mono framework does appear to be installed:

Lees-Mac-Pro:Downloads kevinmack$ cd /Volumes/Macintosh\ HD/Library/Frameworks/
Lees-Mac-Pro:Frameworks kevinmack$ ls -l
total 32
lrwxr-xr-x  1 root  wheel   71 Jan 20  2015 AEProfiling.framework -> ../../Applications/Motion.app/Contents/Frameworks/AEProfiling.framework
lrwxr-xr-x  1 root  wheel   74 Jan 20  2015 AERegistration.framework -> ../../Applications/Motion.app/Contents/Frameworks/AERegistration.framework
lrwxr-xr-x  1 root  wheel   74 Jan 20  2015 AudioMixEngine.framework -> ../../Applications/Motion.app/Contents/Frameworks/AudioMixEngine.framework
drwxr-xr-x  8 root  admin  272 Sep 12 11:24 Mono.framework
lrwxr-xr-x  1 root  wheel   60 Sep  9 22:16 NyxAudioAnalysis.framework -> /System/Library/PrivateFrameworks/NyxAudioAnalysis.framework
drwxr-xr-x  5 root  wheel  170 Jan 20  2015 PluginManager.framework
drwxr-xr-x  8 root  wheel  272 Sep  9 22:19 iTunesLibrary.framework

...but it isn't present in /usr/bin and attempting to find its executable using which mono returns nothing.

Body:
Quick Summary:
Atm, the mono framework installer only works correctly if you install it to root.  It will automatically add /Library/Frameworks/Mono.framework/Versions/Current/Commands to $PATH, but I don't know if you will need to add /Library/Frameworks/Mono.framework/Versions/Current/bin/ by hand or if everything just works. (Commands is a symbolic link to bin, but it still may not work)

More in-depth:
I recently installed mono from MonoFramework-MDK-4.8.0.520.macos10.xamarin.universal.pkg.  I installed it to /Volumes/osxapps/ instead of root, but the installation still expected everything to be in root.  It added /Library/Frameworks/Mono.framework/Versions/Current/Commands to $PATH but everything in /Library/Frameworks/Mono.framework/ was just empty directories.  All the files resided in /Volumes/osxapps/Library/Frameworks/Mono.framework/.

Furthermore, a lot of what was in /Volumes/osxapps/Library/Frameworks/Mono.framework/ including Commands were not folders but symbolic links that didn't work because they expected the folders to be in root.  For example: If everything were installed in root,
/Library/Frameworks/Mono.framework/Versions/Current/Commands is a symlink to /Library/Frameworks/Mono.framework/Versions/Current/bin and /Library/Frameworks/Mono.framework/Versions/Current/ is also a symlink.

I added:

export PATH="/Volumes/osxapps/Library/Frameworks/Mono.framework/Versions/4.8.0/bin:$PATH"

to .bash_profile, in ~/, which allowed me to run the commands/executables, but they all died with errors because they were still expecting things to be in root.

So I copied the folder from /Volumes/osxapps/Library/Frameworks to /Library/Frameworks/ and that solved all the errors and things are working properly but now I have two copies of Mono.framework and I didn't want it installed in root in the first place, because root is on an ssd, and space is limited.

A better solution would be to uninstall mono according to the instructions at bottom of this page and then reinstall on root.

However, it would still be better, for me, to install on /Volumes/osxapps/, but I don't know the best way to go about doing that.  (I could probably just recreate a bunch of symbolic links).  I was going to tell the mono-project that their installer mucks everything up if you don't install to root, but I'm not sure the best way to go about doing that either.  So, instead I have posted here, with what I have learned so far, in the hope that it could help someone else.


问:
Eloquent Foreign key constraint is incorrectly formed laravel
I am trying to add a foreign key to the 'users' table.
These are the time stamps of the migration

And this is the code:

```<code>Schema::create('types', function (Blueprint $table) {
        $table->increments('id');
        $table->string('types');
        $table->timestamps();
    });

Schema::create('users', function (Blueprint $table) {
        //...
        $table->integer('type')->length(10)->unsigned();
        $table->foreign('type')->references('id')->on('types')->onDelete('cascade');
        $table->rememberToken();
        $table->timestamps();
    });
</code>```

I really don't know what I do wrong.

EDIT
Here is what happens after the suggestions which I received

答:
Try to add the foreign key only after you created the table, i.e:

```<code>public function up()
{
    Schema::create('users', function (Blueprint $table) {
        //...
        // $table->integer('type')->length(10)->unsigned();
        $table->unsignedInteger('type');
        $table->rememberToken();
        $table->timestamps();
    });

    Schema::table('users', function (Blueprint $table) {
        $table->foreign('type')->references('id')->on('types')->onDelete('cascade');
    });
}
</code>```

And probably its better to use $table->unsignedInteger('type');

Update:

The conclusion is that type is a reserverd word in MYSQL.

Body:
I am trying to add a foreign key to the 'users' table.
These are the time stamps of the migration

And this is the code:

Schema::create('types', function (Blueprint $table) {
        $table->increments('id');
        $table->string('types');
        $table->timestamps();
    });

Schema::create('users', function (Blueprint $table) {
        //...
        $table->integer('type')->length(10)->unsigned();
        $table->foreign('type')->references('id')->on('types')->onDelete('cascade');
        $table->rememberToken();
        $table->timestamps();
    });

I really don't know what I do wrong.

EDIT
Here is what happens after the suggestions which I received

Body:
Try to add the foreign key only after you created the table, i.e:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        //...
        // $table->integer('type')->length(10)->unsigned();
        $table->unsignedInteger('type');
        $table->rememberToken();
        $table->timestamps();
    });

    Schema::table('users', function (Blueprint $table) {
        $table->foreign('type')->references('id')->on('types')->onDelete('cascade');
    });
}

And probably its better to use $table->unsignedInteger('type');

Update:

The conclusion is that type is a reserverd word in MYSQL.


问:
populating dictionary throws NullReferenceEexception
I have a class with a string and dictionary properties:

```<code>public class Student
{
    public int StudentId { get; set; }
    public Dictionary<string, decimal> LevelGpa { get; set; }
}
</code>```

Which I am trying to populate into a list of Students:

```<code>List<Student> students = new List<Student>()
{
    {new Student{StudentId = 1, LevelGpa = {{"Freshmen",3.1m}}}},
    {new Student{StudentId = 1, LevelGpa = {{"Sophomore",3.2m}}}},
    ...
};
</code>```

But it is throwing a NullReferenceException at run time -

Object reference not set to an instance of an object.

What am I missing here?

答:
You should create an instance of LevelGpa inside each instance of Student object:</p>

```<code>List<Student> students = new List<Student>()
{
    {new Student() {
                    StudentId = 1,
                    LevelGpa = new Dictionary<string, decimal>() {"Freshmen",3.1m}
                   }
    },

    ...
};
</code>```

Body:
I have a class with a string and dictionary properties:

public class Student
{
    public int StudentId { get; set; }
    public Dictionary<string, decimal> LevelGpa { get; set; }
}

Which I am trying to populate into a list of Students:

List<Student> students = new List<Student>()
{
    {new Student{StudentId = 1, LevelGpa = {{"Freshmen",3.1m}}}},
    {new Student{StudentId = 1, LevelGpa = {{"Sophomore",3.2m}}}},
    ...
};

But it is throwing a NullReferenceException at run time -

Object reference not set to an instance of an object.

What am I missing here?

Body:
You should create an instance of LevelGpa inside each instance of Student object:

List<Student> students = new List<Student>()
{
    {new Student() {
                    StudentId = 1,
                    LevelGpa = new Dictionary<string, decimal>() {"Freshmen",3.1m}
                   }
    },

    ...
};


问:
Compare 3 Columns in Excel using VBA
I want to compare 2 to 1 Columns in Excel using VBA..

I already achieve 2 to 2 Columns using this code

```<code>Sub LIST1_LIST2()
    Dim list1 As Range
    Dim LIST2 As Range
    Set list1 = Range("B3:C181")
    Set LIST2 = Range("G3:H729")

    For Each row1 In list1.Rows
        For Each row2 In LIST2.Rows
          If (row1.Cells(1) = row2.Cells(1) And row1.Cells(2) = row2.Cells(2)) Then
              row1.Cells(1).Offset(0, 2) = row1.Cells(1)
              row1.Cells(2).Offset(0, 2) = row1.Cells(2)
              Exit For
          End If
        Next row2

    Next row1

End Sub
</code>```

But now I need something VBA scripts that works somehow like the image below

答:
Work with a a simple Do Until Loop:

```<code>Option Explicit
Public Sub Example()
    Dim B As Range, _
        C As Range, _
        D As Range, _
        F As Range, _
        G As Range

    Dim i%, x% ' Dim as long

    Set B = Columns(2)
    Set C = Columns(3)
    Set D = Columns(4)
    Set F = Columns(6)
    Set G = Columns(7)

    i = 2
    x = 2

    Do Until IsEmpty(B.Cells(i))

        Debug.Print B.Cells(i).Value & ", " & _
                    C.Cells(i).Value ' Print on Immed Win

        Do Until IsEmpty(F.Cells(x))
            DoEvents ' For testing

            If F.Cells(x).Value = B.Cells(i).Value & ", " & _
                                  C.Cells(i).Value Then

               Debug.Print F.Cells(i).Value = B.Cells(i).Value & ", " & _
                           C.Cells(i).Value ' Print on Immed Win

                G.Cells(x) = D.Cells(i)
                x = 2 ' Reset Loop
                Exit Do
            End If

            x = x + 1
        Loop

        i = i + 1
    Loop
End Sub
</code>```

Other info

  DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file. For long-running processes, yielding the processor is better accomplished by using a Timer or delegating the task to an ActiveX EXE component.. In the latter case, the task can continue completely independent of your application, and the operating system takes case of multitasking and time slicing.

Debug.Print Immediate Window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging. To display the Immediate window, open a project for editing, then choose Windows from the Debug menu and select Immediate, or press CTRL+ALT+I.

Title: Compare 3 Columns in Excel using VBA

Body:
I want to compare 2 to 1 Columns in Excel using VBA..

I already achieve 2 to 2 Columns using this code

Sub LIST1_LIST2()
    Dim list1 As Range
    Dim LIST2 As Range
    Set list1 = Range("B3:C181")
    Set LIST2 = Range("G3:H729")

    For Each row1 In list1.Rows
        For Each row2 In LIST2.Rows
          If (row1.Cells(1) = row2.Cells(1) And row1.Cells(2) = row2.Cells(2)) Then
              row1.Cells(1).Offset(0, 2) = row1.Cells(1)
              row1.Cells(2).Offset(0, 2) = row1.Cells(2)
              Exit For
          End If
        Next row2

    Next row1

End Sub

But now I need something VBA scripts that works somehow like the image below

Body:
Work with a a simple Do Until Loop:

Option Explicit
Public Sub Example()
    Dim B As Range, _
        C As Range, _
        D As Range, _
        F As Range, _
        G As Range

    Dim i%, x% ' Dim as long

    Set B = Columns(2)
    Set C = Columns(3)
    Set D = Columns(4)
    Set F = Columns(6)
    Set G = Columns(7)

    i = 2
    x = 2

    Do Until IsEmpty(B.Cells(i))

        Debug.Print B.Cells(i).Value & ", " & _
                    C.Cells(i).Value ' Print on Immed Win

        Do Until IsEmpty(F.Cells(x))
            DoEvents ' For testing

            If F.Cells(x).Value = B.Cells(i).Value & ", " & _
                                  C.Cells(i).Value Then

               Debug.Print F.Cells(i).Value = B.Cells(i).Value & ", " & _
                           C.Cells(i).Value ' Print on Immed Win

                G.Cells(x) = D.Cells(i)
                x = 2 ' Reset Loop
                Exit Do
            End If

            x = x + 1
        Loop

        i = i + 1
    Loop
End Sub

Other info

  DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file. For long-running processes, yielding the processor is better accomplished by using a Timer or delegating the task to an ActiveX EXE component.. In the latter case, the task can continue completely independent of your application, and the operating system takes case of multitasking and time slicing.

Debug.Print Immediate Window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging. To display the Immediate window, open a project for editing, then choose Windows from the Debug menu and select Immediate, or press CTRL+ALT+I.


问:
Function in React ES6 class doesn't change state
```<code>class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      generations: 0,
      rows: 30,
      cols: 30,
      isGoing: false,
      speed: 500,
      gameField: []
    }

    this.generateGameField()
  }

  generateGameField() {
    var result = [];
    for (let i = 0; i < this.state.rows; i++) {
      result[i] = [];
      for (let j = 0; j < this.state.cols; j++) {
        result[i][j] = Math.round(Math.random());
      }
    }
    console.log(result)
    this.setState({ gameField: result })

  }

  render() {
    return (
      <button onClick={() => console.log(this.state)}>Click me</button>
    )
  }

}

ReactDOM.render(
  <Main />,
  document.body
)
</code>```

Please help me. Function generateGameField supposed to create new array and fill it with 0 or 1. The function actually create array, but doesn't change state. Within the function I have access to the state, so I just don't know what went wrong

答:
It seems to me you are trying to initialize the component. If that's what you want to achieve then you should use the react life cycle method; componentWillMount.

So to fix the bug, rename generateGameField function to componentWillMount and reorganize the code as below:

```<code>  class Main extends React.Component {
     constructor(props) {
       super(props);
     }

     componentWillMount() {
       let result = [];
       const rows = 30;
       const cols = 30;
       for (let i = 0; i < rows; i++) {
           result[i] = [];
           for (let j = 0; j < cols; j++) {
              result[i][j] = Math.round(Math.random());
           }
       }
       console.log(result)
       this.setState({
         generations: 0,
         rows: 30,
         cols: 30,
         isGoing: false,
         speed: 500,
         gameField: result
       })

     }

     render() {
        return (
        <button onClick={() => console.log(this.state)}>Click me</button>
        )
     }

 }

 ReactDOM.render(<Main />,document.body)
</code>```

This what I found in the react official documentation:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

This is the only lifecycle hook called on server rendering. Generally, we recommend using the constructor() instead.

Abiding by that the above code could be modified to:

```<code>  class Main extends React.Component {
     constructor(props) {
       super(props);
       let result = [];
       const rows = 30;
       const cols = 30;
       for (let i = 0; i < rows; i++) {
           result[i] = [];
           for (let j = 0; j < cols; j++) {
              result[i][j] = Math.round(Math.random());
           }
       }
       console.log(result);
       this.state = {
         generations: 0,
         rows: 30,
         cols: 30,
         isGoing: false,
         speed: 500,
         gameField: result
       };
     }

     render() {
        return (
        <button onClick={() => console.log(this.state)}>Click me</button>
        )
     }

 }

 ReactDOM.render(<Main />,document.body)
</code>```

Body:
class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      generations: 0,
      rows: 30,
      cols: 30,
      isGoing: false,
      speed: 500,
      gameField: []
    }

    this.generateGameField()
  }

  generateGameField() {
    var result = [];
    for (let i = 0; i < this.state.rows; i++) {
      result[i] = [];
      for (let j = 0; j < this.state.cols; j++) {
        result[i][j] = Math.round(Math.random());
      }
    }
    console.log(result)
    this.setState({ gameField: result })

  }

  render() {
    return (
      <button onClick={() => console.log(this.state)}>Click me</button>
    )
  }

}

ReactDOM.render(
  ,
  document.body
)

Please help me. Function generateGameField supposed to create new array and fill it with 0 or 1. The function actually create array, but doesn't change state. Within the function I have access to the state, so I just don't know what went wrong

Body:
It seems to me you are trying to initialize the component. If that's what you want to achieve then you should use the react life cycle method; componentWillMount.

So to fix the bug, rename generateGameField function to componentWillMount and reorganize the code as below:

  class Main extends React.Component {
     constructor(props) {
       super(props);
     }

     componentWillMount() {
       let result = [];
       const rows = 30;
       const cols = 30;
       for (let i = 0; i < rows; i++) {
           result[i] = [];
           for (let j = 0; j < cols; j++) {
              result[i][j] = Math.round(Math.random());
           }
       }
       console.log(result)
       this.setState({
         generations: 0,
         rows: 30,
         cols: 30,
         isGoing: false,
         speed: 500,
         gameField: result
       })

     }

     render() {
        return (
        <button onClick={() => console.log(this.state)}>Click me</button>
        )
     }

 }

 ReactDOM.render(<Main />,document.body)

This what I found in the react official documentation:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

This is the only lifecycle hook called on server rendering. Generally, we recommend using the constructor() instead.

Abiding by that the above code could be modified to:

  class Main extends React.Component {
     constructor(props) {
       super(props);
       let result = [];
       const rows = 30;
       const cols = 30;
       for (let i = 0; i < rows; i++) {
           result[i] = [];
           for (let j = 0; j < cols; j++) {
              result[i][j] = Math.round(Math.random());
           }
       }
       console.log(result);
       this.state = {
         generations: 0,
         rows: 30,
         cols: 30,
         isGoing: false,
         speed: 500,
         gameField: result
       };
     }

     render() {
        return (
        <button onClick={() => console.log(this.state)}>Click me</button>
        )
     }

 }

 ReactDOM.render(<Main />,document.body)


问:
Print a file in Python on Windows without opening it
Running the following line of python causes Adobe Acrobat to launch

```<code>win32api.ShellExecute(0, "print", "myC.pdf", None, ".", 0)
</code>```

Adobe is my default PDF viewer. Why is Adobe opening? How can I prevent this from happening?

The script meant to run many times on a slow PC.

I do not understand how print works from ShellExecute. Typing print myC.pdf in the command prompt gives me the error "Unable to initialize device PRN". A little background would be appreciated.

答:
printing the file at the system level is a command to display the file.  Adobe's viewer is the application associated with this file.  What are you expecting to happen?  If you want to operate on the file with some other application, then you'll have to specify that through a more focused interface.

print is equivalent to the GUI sequence right-clink + Print.  The first thing that print does is to open the file; Windows doesn't have a default interface to print a file without opening it normally.

I found you a couple of references that know even more than I do:  :-)

A related SO question

The MS documentation on ShellExecute

Body:
Running the following line of python causes Adobe Acrobat to launch

win32api.ShellExecute(0, "print", "myC.pdf", None, ".", 0)

Adobe is my default PDF viewer. Why is Adobe opening? How can I prevent this from happening?

The script meant to run many times on a slow PC.

I do not understand how print works from ShellExecute. Typing print myC.pdf in the command prompt gives me the error "Unable to initialize device PRN". A little background would be appreciated.


问:
javascript script title from objective C
I am trying to call a simple javascript title from objective C.. however title always return as empty. If i change the string to a random string, title would return the random string. Meaning i am doing [webView] wrongly? whats is wrong? thankss</p>

```<code>- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // Add code to open bundled Web site

    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

    NSString *path = @"http://www.test.net";

    NSURL *url = [NSURL URLWithString:path];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [webView loadRequest:request];

    NSLog(@"%@",title);

    // Override point for customization after application launch
    [window makeKeyAndVisible];}
</code>```

答:
You're evaluating that javascript before the webview has even loaded the page.

You should set a delegate for your UIWebView. Then the delegate should implement webViewDidFinishLoad:

When that delegate method is called, you can be sure the page has loaded and then you will be able to get the title.

Body:
I am trying to call a simple javascript title from objective C.. however title always return as empty. If i change the string to a random string, title would return the random string. Meaning i am doing [webView] wrongly? whats is wrong? thankss

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // Add code to open bundled Web site

    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

    NSString *path = @"http://www.test.net";

    NSURL *url = [NSURL URLWithString:path];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [webView loadRequest:request];

    NSLog(@"%@",title);

    // Override point for customization after application launch
    [window makeKeyAndVisible];}


问:
Jinja2 looping through dict with control over what key:value is used
I'm trying to create a table in HTML from data passed to the web as dict

app.py:

```<code>client = boto3.client('ec2')
vpc_ids = client.describe_vpcs()
for i in vpc_ids.get('Vpcs'):
    for tag in i.get('Tags'):
        if tag.get('Key') == 'Name':
            vpc_list[i.get('VpcId')] = {'CidrBlock': i.get('CidrBlock'),
            'Name': tag.get('Value')}
return vpc_list
</code>```

This returnes dict like this:

```<code>vpc_list = {'vpc-1': {'CidrBlock': 'x.x.x.x/16', 'Name': 'a-vpc'},
            'vpc-2': {'CidrBlock': 'y.y.y.y/16', 'Name': 'b-vpc'},
            'vpc-3': {'CidrBlock': 'z.z.z.z/16', 'Name': 'c-vpc'},
            'vpc-4': {'CidrBlock': 'q.q.q.q/16', 'Name': 'd-vpc'}}
</code>```

My HTML looks like this:

```<code><div class="container">
{% if vpc_lists is defined %}
{% for vpc, data in vpc_lists.items() %}
<div class="row">
    <div class="col-md-1">
        <i class="fa fa-camera-retro fa-lg"></i>
    </div>
    <div class="col-md-3">
        {{vpc}}
    </div>
    {% for key,value in data.items() %}
    <div class="col-md-3">
        {{value}}
    </div>
    {% endfor %}
    <div class="col-md-2">
        <a href="/vpc/{{vpc}}">Link</a>
    </div>
</div>
{% endfor %}
{% endif %}
</code>```

The Above works... kind off, but I would like better control over how and where I can use key values, so instead of just blindly looping through this I would like to be able to get a value based on the key, something like

```<code>vpc.get('CidrBlock') or vpc['CidrBlock'] to get the x.x.x.x/16 value.
</code>```

Not sure if I'm making it clear enough. I couldn't find anything like this in here.

答: Jinja supports dictionary access syntax, you can use {{data['CidrBlock']}} and {{data['Name']}} to access specific values in your dictionary.

Body:
I'm trying to create a table in HTML from data passed to the web as dict

app.py:

client = boto3.client('ec2')
vpc_ids = client.describe_vpcs()
for i in vpc_ids.get('Vpcs'):
    for tag in i.get('Tags'):
        if tag.get('Key') == 'Name':
            vpc_list[i.get('VpcId')] = {'CidrBlock': i.get('CidrBlock'),
            'Name': tag.get('Value')}
return vpc_list

This returnes dict like this:

vpc_list = {'vpc-1': {'CidrBlock': 'x.x.x.x/16', 'Name': 'a-vpc'},
            'vpc-2': {'CidrBlock': 'y.y.y.y/16', 'Name': 'b-vpc'},
            'vpc-3': {'CidrBlock': 'z.z.z.z/16', 'Name': 'c-vpc'},
            'vpc-4': {'CidrBlock': 'q.q.q.q/16', 'Name': 'd-vpc'}}

My HTML looks like this:

{% if vpc_lists is defined %}
{% for vpc, data in vpc_lists.items() %}

        {{vpc}}

    {% for key,value in data.items() %}

        {{value}}

    {% endfor %}

        Link

{% endfor %}
{% endif %}

The Above works... kind off, but I would like better control over how and where I can use key values, so instead of just blindly looping through this I would like to be able to get a value based on the key, something like

vpc.get('CidrBlock') or vpc['CidrBlock'] to get the x.x.x.x/16 value.

Not sure if I'm making it clear enough. I couldn't find anything like this in here.


问:
Mocking AWS lambda and boto3
I have a lambda (python) which returns a json representation of a customer profile.  It does this by starting with a top level account json, then reading linked json files until it runs out of links.  The function that does the reading from s3 is recursive, but the recursion will only ever be one level deep.

Here's the method that actually gets the json content from a given key. (bucket is known)

```<code>def get_index_from_s3(key):
    try:
        response = s3.get_object(
            Bucket=bucket,
            Key=key
        )
        body = response.get('Body')
        content = body.read().decode('utf-8')
    except ClientError as ex:
        # print 'EXCEPTION MESSAGE: {}'.format(ex.response['Error']['Code'])
        content = '{}'

    message = json.loads(content)
    return message
</code>```

The code returns the json found at the specified key, or an empty dictionary in the event that get_object fails due to a ClientError (which is what results from NoSuchKey).

I've tested this, and it works.  The first call to the function gets a chunk of json. That json is parsed, a link is found, a second call is made, and the profile is built.  If I delete the object at the linked key, I just get a default, empty representation, as intended.

My problem comes from testing this.
I've written a couple of test classes, each has an arrange method, and they share an act method.

For my happy path, I use the following arrange:

```<code>def arrange(self):
    super(WhenCognitoAndNerfFoundTestCase, self).arrange()
    # self.s3_response = self.s3.get_object.return_value
    self.s3_body = self.s3.get_object.return_value.get.return_value
    self.s3_body.read.return_value.decode.side_effect = [
        self.cognito_content,
        self.nerf_content]
    signed_url = "https://this.is/a/signed/url/index.html"
    self.s3.generate_presigned_url.return_value = signed_url
</code>```

This does exactly what I want.  s3_response is the return_value of get_object, which has a Body attribute returned by get, and a subsequent read value returns a json string.  I use the side_effect set to a list of json strings so that I can cause a different string to be returned on each call (only two)
content = body.read().decode('utf-8')

But when I want to test the case of missing content in the second bucket, I get stymied. My current attempt at this arrangement is as follows:

```<code>def arrange(self):
    super(WhenCognitoOnlyFoundTestCase, self).arrange()
    # self.s3_response = MagicMock()
    # botocore.response.StreamingBody
    self.s3.get_object.side_effect = [{},
                                      ClientError]
    # self.s3_response = self.s3.get_object.return_value
    self.s3_body = self.s3.get_object.return_value.get.return_value
    self.s3_body.read.return_value.decode.return_value = \
        self.cognito_content
</code>```

Running the test yields this:

```<code>    def get_index_from_s3(key):
        try:
            response  = s3.get_object(
                Bucket=bucket,
                Key=key
            )
            body = response.get('Body')
>           content = body.read().decode('utf-8')
E            AttributeError: 'NoneType' object has no attribute 'read'

master_profile.py:66: AttributeError
</code>```

This makes sense because the read method is on the Body attribute of the s3.get_object response, which is None in this scenario.

So my question is, how do I mock this thing so that I can test it?  The difficulty of mocking a response of get_object is that, although it's just a dictionary, the Body attribute is a botocore.response.StreamingBody which I do not know how to mock.

答:
As a rule of thumb you should aim to make your questions self-contained. To illustrate some of the things you were doing wrong I slightly modified your initial function to make it self-contained.

Let's imagine we have the s3_module we want to test defined as follows:

```<code>import boto3
from botocore.exceptions import ClientError
import json

s3 = boto3.client('s3')

def get_index_from_s3(key):
    try:
        response = s3.get_object(
            Bucket='bucket',
            Key=key
        )
        body = response.get('Body')
        content = body.read().decode('utf-8')
    except ClientError as ex:
        import ipdb; ipdb.set_trace()
        # print 'EXCEPTION MESSAGE: {}'.format(ex.response['Error']['Code'])
        content = '{}'

    message = json.loads(content)
    return message
</code>```

In order to test it, we could write a another module s3_test with a test similar to this:

```<code>import pytest
from unittest.mock import patch, Mock, MagicMock
from botocore.exceptions import ClientError
import json

from s3_module import get_index_from_s3

@patch('s3_module.s3.get_object')
def test_get_index_from_s3(s3_get_mock):

    body_mock = Mock()
    body_mock.read.return_value.decode.return_value = json.dumps('first_response')
    s3_get_mock.side_effect = [{'Body': body_mock}, ClientError(MagicMock(), MagicMock())]

    first_response = get_index_from_s3('key1')
    assert  first_response == 'first_response'
    second_response = get_index_from_s3('key2')
    assert  second_response == {}
</code>```

Compared to your solution you were missing some points:

self.s3.get_object.side_effect should return an object for the first response that works with the rest of your code, i.e. a dictionary containing the Body key whose content can be read(), decoded() and be used by json.load()

self.s3.get_object.side_effect should return a ClientError exception properly constructed for the second response

You can check more about how to build the ClientError exception in the botocore docs: http://botocore.readthedocs.io/en/latest/client_upgrades.html#error-handling

You can find more about patching and mocking in the docs: https://docs.python.org/3/library/unittest.mock.html.

Usually the section about where to patch is really useful: https://docs.python.org/3/library/unittest.mock.html#where-to-patch

Title: Mocking AWS lambda and boto3

Body:
I have a lambda (python) which returns a json representation of a customer profile.  It does this by starting with a top level account json, then reading linked json files until it runs out of links.  The function that does the reading from s3 is recursive, but the recursion will only ever be one level deep.

Here's the method that actually gets the json content from a given key. (bucket is known)

def get_index_from_s3(key):
    try:
        response = s3.get_object(
            Bucket=bucket,
            Key=key
        )
        body = response.get('Body')
        content = body.read().decode('utf-8')
    except ClientError as ex:
        # print 'EXCEPTION MESSAGE: {}'.format(ex.response['Error']['Code'])
        content = '{}'

    message = json.loads(content)
    return message

The code returns the json found at the specified key, or an empty dictionary in the event that get_object fails due to a ClientError (which is what results from NoSuchKey).

I've tested this, and it works.  The first call to the function gets a chunk of json. That json is parsed, a link is found, a second call is made, and the profile is built.  If I delete the object at the linked key, I just get a default, empty representation, as intended.

My problem comes from testing this.
I've written a couple of test classes, each has an arrange method, and they share an act method.

For my happy path, I use the following arrange:

def arrange(self):
    super(WhenCognitoAndNerfFoundTestCase, self).arrange()
    # self.s3_response = self.s3.get_object.return_value
    self.s3_body = self.s3.get_object.return_value.get.return_value
    self.s3_body.read.return_value.decode.side_effect = [
        self.cognito_content,
        self.nerf_content]
    signed_url = "https://this.is/a/signed/url/index.html"
    self.s3.generate_presigned_url.return_value = signed_url

This does exactly what I want.  s3_response is the return_value of get_object, which has a Body attribute returned by get, and a subsequent read value returns a json string.  I use the side_effect set to a list of json strings so that I can cause a different string to be returned on each call (only two)
content = body.read().decode('utf-8')

But when I want to test the case of missing content in the second bucket, I get stymied. My current attempt at this arrangement is as follows:

def arrange(self):
    super(WhenCognitoOnlyFoundTestCase, self).arrange()
    # self.s3_response = MagicMock()
    # botocore.response.StreamingBody
    self.s3.get_object.side_effect = [{},
                                      ClientError]
    # self.s3_response = self.s3.get_object.return_value
    self.s3_body = self.s3.get_object.return_value.get.return_value
    self.s3_body.read.return_value.decode.return_value = \
        self.cognito_content

Running the test yields this:

    def get_index_from_s3(key):
        try:
            response  = s3.get_object(
                Bucket=bucket,
                Key=key
            )
            body = response.get('Body')
>           content = body.read().decode('utf-8')
E            AttributeError: 'NoneType' object has no attribute 'read'

master_profile.py:66: AttributeError

This makes sense because the read method is on the Body attribute of the s3.get_object response, which is None in this scenario.

So my question is, how do I mock this thing so that I can test it?  The difficulty of mocking a response of get_object is that, although it's just a dictionary, the Body attribute is a botocore.response.StreamingBody which I do not know how to mock.

Body:
As a rule of thumb you should aim to make your questions self-contained. To illustrate some of the things you were doing wrong I slightly modified your initial function to make it self-contained.

Let's imagine we have the s3_module we want to test defined as follows:

import boto3
from botocore.exceptions import ClientError
import json

s3 = boto3.client('s3')

def get_index_from_s3(key):
    try:
        response = s3.get_object(
            Bucket='bucket',
            Key=key
        )
        body = response.get('Body')
        content = body.read().decode('utf-8')
    except ClientError as ex:
        import ipdb; ipdb.set_trace()
        # print 'EXCEPTION MESSAGE: {}'.format(ex.response['Error']['Code'])
        content = '{}'

    message = json.loads(content)
    return message

In order to test it, we could write a another module s3_test with a test similar to this:

import pytest
from unittest.mock import patch, Mock, MagicMock
from botocore.exceptions import ClientError
import json

from s3_module import get_index_from_s3

@patch('s3_module.s3.get_object')
def test_get_index_from_s3(s3_get_mock):

    body_mock = Mock()
    body_mock.read.return_value.decode.return_value = json.dumps('first_response')
    s3_get_mock.side_effect = [{'Body': body_mock}, ClientError(MagicMock(), MagicMock())]

    first_response = get_index_from_s3('key1')
    assert  first_response == 'first_response'
    second_response = get_index_from_s3('key2')
    assert  second_response == {}

Compared to your solution you were missing some points:

self.s3.get_object.side_effect should return an object for the first response that works with the rest of your code, i.e. a dictionary containing the Body key whose content can be read(), decoded() and be used by json.load()

self.s3.get_object.side_effect should return a ClientError exception properly constructed for the second response

You can check more about how to build the ClientError exception in the botocore docs: http://botocore.readthedocs.io/en/latest/client_upgrades.html#error-handling

You can find more about patching and mocking in the docs: https://docs.python.org/3/library/unittest.mock.html.

Usually the section about where to patch is really useful: https://docs.python.org/3/library/unittest.mock.html#where-to-patch


问:
How to import debug into a TypeScript project you'll use rollup on?
I've got an Angular 2 project and have been using debug with no problems.  I'm now trying to use rollup and I get the error:

```<code>Cannot call a namespace ('debugModule')
</code>```

This refers to the way I import debug:

```<code>import * as debugModule from 'debug';
</code>```

I've seen that the solution to this is to import without using the * as someName syntax, like this:

```<code>import debug from 'debug';
</code>```

or maybe:

```<code>import { Debug } from 'debug';
</code>```

...but neither of those work (has no default export and has no exported member 'Debug').  I've done my best to look at the source of both debug and @types/debug
to see what I should import, but all I can see is from @types/debug - there are IDebug and IDebugger interfaces which aren't what I'm looking for.

How should I be importing debug such that rollup will be OK with it?

It looks like I can coerce it into working by calling it this way:

```<code>debug = debugModule.call(this, 'module:component');
</code>```

Although I'm not sure what repercussions that might have going forward...

答: So I don't know why, but if you have installed @types/debug then import debug from 'debug' won't work, but if you just remove @types/debug then you can import it.  This doesn't solve all the problems I have with debug when using rollup, but it stops the Cannot call namespace problem and you can call debug normally.

Body:
I've got an Angular 2 project and have been using debug with no problems.  I'm now trying to use rollup and I get the error:

Cannot call a namespace ('debugModule')

This refers to the way I import debug:

import * as debugModule from 'debug';

I've seen that the solution to this is to import without using the * as someName syntax, like this:

import debug from 'debug';

or maybe:

import { Debug } from 'debug';

...but neither of those work (has no default export and has no exported member 'Debug').  I've done my best to look at the source of both debug and @types/debug
to see what I should import, but all I can see is from @types/debug - there are IDebug and IDebugger interfaces which aren't what I'm looking for.

How should I be importing debug such that rollup will be OK with it?

It looks like I can coerce it into working by calling it this way:

debug = debugModule.call(this, 'module:component');

Although I'm not sure what repercussions that might have going forward...


问:
alfresco and ldap configuration
I am currently configuring alfresco to use ldap server  for authentication.
I followed the offecial documentation and i updated alfresco-global.properties file but it dosen't work.
i am using alfresco 5.2 and this is my alfresco-global.properties file and the ldap hiarchy.

```<code>###############################
## Common Alfresco Properties #
###############################

dir.root=C:/ALFRES~1/alf_data

alfresco.context=alfresco
alfresco.host=127.0.0.1
alfresco.port=8080
alfresco.protocol=http

share.context=share
share.host=127.0.0.1
share.port=8080
share.protocol=http

### database connection properties ###
db.driver=org.postgresql.Driver
db.username=alfresco
db.password=admin
db.name=alfresco
db.url=jdbc:postgresql://localhost:5432/${db.name}
# Note: your database must also be able to accept at least this many connections.  Please see your database documentation for instructions on how to configure this.
db.pool.max=275
db.pool.validate.query=SELECT 1

# The server mode. Set value here
# UNKNOWN | TEST | BACKUP | PRODUCTION
system.serverMode=UNKNOWN

### FTP Server Configuration ###
ftp.port=21

### RMI registry port for JMX ###
alfresco.rmi.services.port=50500

### External executable locations ###
ooo.exe=C:/ALFRES~1/LIBREO~1/App/libreoffice/program/soffice.exe
ooo.enabled=true
ooo.port=8100
img.root=C:\\alfresco-community\\imagemagick
img.coders=${img.root}\\modules\\coders
img.config=${img.root}
img.gslib=${img.root}\\lib
img.exe=${img.root}\\convert.exe

jodconverter.enabled=false
jodconverter.officeHome=C:/ALFRES~1/LIBREO~1/App/libreoffice
jodconverter.portNumbers=8100

### Initial admin password ###
alfresco_user_store.adminpassword=209c6174da490caeb422f3fa5a7ae634

### E-mail site invitation setting ###
notification.email.siteinvite=false

### License location ###
dir.license.external=C:/ALFRES~1

### Solr indexing ###
index.subsystem.name=solr4
dir.keystore=${dir.root}/keystore
solr.host=localhost
solr.port.ssl=8443

### Allow extended ResultSet processing
security.anyDenyDenies=false

### Smart Folders Config Properties ###
smart.folders.enabled=false

### Remote JMX (Default: disabled) ###
alfresco.jmx.connector.enabled=false

### Remote JMX (Default: disabled) ###
alfresco.jmx.connector.enabled=false

authentication.chain=alfinst:alfrescoNtlm,ldap1:ldap

ntlm.authentication.sso.enabled=false

ldap.authentication.allowGuestLogin=false
ldap.authentication.userNameFormat=%s
ldap.authentication.java.naming.provider.url=ldap://localhost:10389
ldap.authentication.defaultAdministratorUserNames=Administrator,alfresco
ldap.synchronization.java.naming.security.principal=admin
ldap.synchronization.java.naming.security.credentials=secret
ldap.synchronization.groupSearchBase=ou=groups,o=mojo
ldap.synchronization.userSearchBase=ou=users,o=mojo
</code>```

My Log

```<code>mars 30, 2017 4:05:46 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
mars 30, 2017 4:05:46 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
mars 30, 2017 4:05:47 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFOS: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:05:50 PM org.apache.catalina.startup.Catalina load
INFOS: Initialization processed in 5988 ms
mars 30, 2017 4:05:50 PM org.apache.catalina.core.StandardService startInternal
INFOS: Démarrage du service Catalina
mars 30, 2017 4:05:50 PM org.apache.catalina.core.StandardEngine startInternal
INFOS: Starting Servlet Engine: Apache Tomcat/7.0.x
mars 30, 2017 4:05:50 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml
mars 30, 2017 4:07:38 PM org.apache.catalina.core.StandardContext startInternal
GRAVE: Error listenerStart
mars 30, 2017 4:07:38 PM org.apache.catalina.core.StandardContext startInternal
GRAVE: Erreur de démarrage du contexte [/alfresco] suite aux erreurs précédentes
mars 30, 2017 4:07:38 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml has finished in 108 389 ms
mars 30, 2017 4:07:38 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml has finished in 86 895 ms
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '0' did not find a matching property.
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml has finished in 34 391 ms
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\ROOT.war de l'application web
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '100' did not find a matching property.
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\ROOT.war has finished in 547 ms
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\_vti_bin.war de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\_vti_bin.war has finished in 711 ms
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\host-manager de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\host-manager has finished in 285 ms
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\manager de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\manager has finished in 244 ms
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.Catalina start
INFOS: Server startup in 231821 ms
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:11:26 PM org.apache.catalina.core.StandardService stopInternal
INFOS: Arrêt du service Catalina
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:12:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
mars 30, 2017 4:12:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
mars 30, 2017 4:12:35 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFOS: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:12:37 PM org.apache.catalina.startup.Catalina load
INFOS: Initialization processed in 4101 ms
mars 30, 2017 4:12:37 PM org.apache.catalina.core.StandardService startInternal
INFOS: Démarrage du service Catalina
mars 30, 2017 4:12:37 PM org.apache.catalina.core.StandardEngine startInternal
INFOS: Starting Servlet Engine: Apache Tomcat/7.0.x
mars 30, 2017 4:12:37 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml
mars 30, 2017 4:15:22 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml has finished in 164 795 ms
mars 30, 2017 4:15:22 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml has finished in 34 374 ms
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '0' did not find a matching property.
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml has finished in 28 614 ms
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\ROOT.war de l'application web
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '100' did not find a matching property.
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\ROOT.war has finished in 479 ms
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\_vti_bin.war de l'application web
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\_vti_bin.war has finished in 619 ms
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\host-manager de l'application web
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\host-manager has finished in 337 ms
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\manager de l'application web
mars 30, 2017 4:16:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\manager has finished in 260 ms
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:16:27 PM org.apache.catalina.startup.Catalina start
INFOS: Server startup in 229832 ms
</code>```

答:
It is hard to tell what the problem is without any error messages or exceptions, but you might want to try adjusting the userNameFormat. For example, instead of %s, it is likely that it needs to be something like:

```<code>ldap.authentication.userNameFormat=uid=%s,ou=users,o=mojo
</code>```

But, again, it is hard to tell without more info.

Title: alfresco and ldap configuration

Body:
I am currently configuring alfresco to use ldap server  for authentication.
I followed the offecial documentation and i updated alfresco-global.properties file but it dosen't work.
i am using alfresco 5.2 and this is my alfresco-global.properties file and the ldap hiarchy.

###############################
## Common Alfresco Properties #
###############################

dir.root=C:/ALFRES~1/alf_data

alfresco.context=alfresco
alfresco.host=127.0.0.1
alfresco.port=8080
alfresco.protocol=http

share.context=share
share.host=127.0.0.1
share.port=8080
share.protocol=http

### database connection properties ###
db.driver=org.postgresql.Driver
db.username=alfresco
db.password=admin
db.name=alfresco
db.url=jdbc:postgresql://localhost:5432/${db.name}
# Note: your database must also be able to accept at least this many connections.  Please see your database documentation for instructions on how to configure this.
db.pool.max=275
db.pool.validate.query=SELECT 1

# The server mode. Set value here
# UNKNOWN | TEST | BACKUP | PRODUCTION
system.serverMode=UNKNOWN

### FTP Server Configuration ###
ftp.port=21

### RMI registry port for JMX ###
alfresco.rmi.services.port=50500

### External executable locations ###
ooo.exe=C:/ALFRES~1/LIBREO~1/App/libreoffice/program/soffice.exe
ooo.enabled=true
ooo.port=8100
img.root=C:\\alfresco-community\\imagemagick
img.coders=${img.root}\\modules\\coders
img.config=${img.root}
img.gslib=${img.root}\\lib
img.exe=${img.root}\\convert.exe

jodconverter.enabled=false
jodconverter.officeHome=C:/ALFRES~1/LIBREO~1/App/libreoffice
jodconverter.portNumbers=8100

### Initial admin password ###
alfresco_user_store.adminpassword=209c6174da490caeb422f3fa5a7ae634

### E-mail site invitation setting ###
notification.email.siteinvite=false

### License location ###
dir.license.external=C:/ALFRES~1

### Solr indexing ###
index.subsystem.name=solr4
dir.keystore=${dir.root}/keystore
solr.host=localhost
solr.port.ssl=8443

### Allow extended ResultSet processing
security.anyDenyDenies=false

### Smart Folders Config Properties ###
smart.folders.enabled=false

### Remote JMX (Default: disabled) ###
alfresco.jmx.connector.enabled=false

### Remote JMX (Default: disabled) ###
alfresco.jmx.connector.enabled=false

authentication.chain=alfinst:alfrescoNtlm,ldap1:ldap

ntlm.authentication.sso.enabled=false

ldap.authentication.allowGuestLogin=false
ldap.authentication.userNameFormat=%s
ldap.authentication.java.naming.provider.url=ldap://localhost:10389
ldap.authentication.defaultAdministratorUserNames=Administrator,alfresco
ldap.synchronization.java.naming.security.principal=admin
ldap.synchronization.java.naming.security.credentials=secret
ldap.synchronization.groupSearchBase=ou=groups,o=mojo
ldap.synchronization.userSearchBase=ou=users,o=mojo

My Log

mars 30, 2017 4:05:46 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
mars 30, 2017 4:05:46 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
mars 30, 2017 4:05:47 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFOS: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:05:47 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:05:50 PM org.apache.catalina.startup.Catalina load
INFOS: Initialization processed in 5988 ms
mars 30, 2017 4:05:50 PM org.apache.catalina.core.StandardService startInternal
INFOS: Démarrage du service Catalina
mars 30, 2017 4:05:50 PM org.apache.catalina.core.StandardEngine startInternal
INFOS: Starting Servlet Engine: Apache Tomcat/7.0.x
mars 30, 2017 4:05:50 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml
mars 30, 2017 4:07:38 PM org.apache.catalina.core.StandardContext startInternal
GRAVE: Error listenerStart
mars 30, 2017 4:07:38 PM org.apache.catalina.core.StandardContext startInternal
GRAVE: Erreur de démarrage du contexte [/alfresco] suite aux erreurs précédentes
mars 30, 2017 4:07:38 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml has finished in 108 389 ms
mars 30, 2017 4:07:38 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml has finished in 86 895 ms
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml
mars 30, 2017 4:09:05 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '0' did not find a matching property.
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml has finished in 34 391 ms
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\ROOT.war de l'application web
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '100' did not find a matching property.
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\ROOT.war has finished in 547 ms
mars 30, 2017 4:09:40 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\_vti_bin.war de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\_vti_bin.war has finished in 711 ms
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\host-manager de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\host-manager has finished in 285 ms
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\manager de l'application web
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\manager has finished in 244 ms
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:09:41 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:09:41 PM org.apache.catalina.startup.Catalina start
INFOS: Server startup in 231821 ms
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:11:26 PM org.apache.coyote.AbstractProtocol pause
INFOS: Pausing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:11:26 PM org.apache.catalina.core.StandardService stopInternal
INFOS: Arrêt du service Catalina
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:11:57 PM org.apache.coyote.AbstractProtocol stop
INFOS: Stopping ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:12:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: Loaded APR based Apache Tomcat Native library 1.1.32 using APR version 1.5.1.
mars 30, 2017 4:12:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFOS: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
mars 30, 2017 4:12:35 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFOS: OpenSSL successfully initialized (OpenSSL 1.0.1j 15 Oct 2014)
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:12:35 PM org.apache.coyote.AbstractProtocol init
INFOS: Initializing ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:12:37 PM org.apache.catalina.startup.Catalina load
INFOS: Initialization processed in 4101 ms
mars 30, 2017 4:12:37 PM org.apache.catalina.core.StandardService startInternal
INFOS: Démarrage du service Catalina
mars 30, 2017 4:12:37 PM org.apache.catalina.core.StandardEngine startInternal
INFOS: Starting Servlet Engine: Apache Tomcat/7.0.x
mars 30, 2017 4:12:37 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml
mars 30, 2017 4:15:22 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\alfresco.xml has finished in 164 795 ms
mars 30, 2017 4:15:22 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\share.xml has finished in 34 374 ms
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Déploiement du descripteur de configuration C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml
mars 30, 2017 4:15:56 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '0' did not find a matching property.
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFOS: Deployment of configuration descriptor C:\alfresco-community\tomcat\conf\Catalina\localhost\solr4.xml has finished in 28 614 ms
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\ROOT.war de l'application web
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.SetContextPropertiesRule begin
AVERTISSEMENT: [SetContextPropertiesRule]{Context} Setting property 'debug' to '100' did not find a matching property.
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\ROOT.war has finished in 479 ms
mars 30, 2017 4:16:25 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Déploiement de l'archive C:\alfresco-community\tomcat\webapps\_vti_bin.war de l'application web
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployWAR
INFOS: Deployment of web application archive C:\alfresco-community\tomcat\webapps\_vti_bin.war has finished in 619 ms
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\host-manager de l'application web
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\host-manager has finished in 337 ms
mars 30, 2017 4:16:26 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Déploiement du répertoire C:\alfresco-community\tomcat\webapps\manager de l'application web
mars 30, 2017 4:16:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFOS: Deployment of web application directory C:\alfresco-community\tomcat\webapps\manager has finished in 260 ms
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-apr-8080"]
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["ajp-apr-8009"]
mars 30, 2017 4:16:27 PM org.apache.coyote.AbstractProtocol start
INFOS: Starting ProtocolHandler ["http-bio-8443"]
mars 30, 2017 4:16:27 PM org.apache.catalina.startup.Catalina start
INFOS: Server startup in 229832 ms

Body:
It is hard to tell what the problem is without any error messages or exceptions, but you might want to try adjusting the userNameFormat. For example, instead of %s, it is likely that it needs to be something like:

ldap.authentication.userNameFormat=uid=%s,ou=users,o=mojo

But, again, it is hard to tell without more info.


问:
Taking invisible WebRTC/video photos without canvas/display
I've read Taking still photos from MDN describing how you can capture photos from the web cam (using a video element and mediaDevices.getUserMedia) to show them to the user using a canvas.

However I do not need (and do not want) to display the taken image to the user and thus I also do not want to use a canvas as I'd say that first drawing a canvas just to get the image data (as ImageData or DataUri) could be bad for the performance.

So is there a way to get the image data without using canvas?

答:
Using canvas is totally fine and performs well. Just don't attach the canvas to the document and it won't be shown.  I think your concern about performance is unfounded.

The only other way to get data out of a stream would be MediaRecorder but it produces video at a given frame rate, not what you want, and much more involved.

There's talk of an imageCapture API, but it's not implemented in any browser yet, except behind a flag. It would offer a .takePhoto() method which would also give access to full-resolution photo cameras where available (i.e. phones).


问:
How to parse a certain column from a certain line in an ASCII file?
I am trying to parse out a string value from a certain column in a certain line in my ASCII file. Below I have included what I have tried to this point, the error I received when I ran this code is:

Attribute: 'list' object has no attribute 'split'`
```

<p>Code:</p>

```import numpy as np
import matplotlib.pyplot as plt

f = open('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 'r')

line = f.readlines(49)
columns = line.split()
time = columns(2)
print (time)

f.close()
```

答:
I would create a function to do it.

Note that line and column number are counted from 1, not zero.

```<code>def find_line_and_column(filename, line_num, column_num):
    with open(filename, 'r') as file:
        for i in range(line_num-1):  # skip over lines before the desired one
            next(file)
        line = next(file)  # read the desired line
        return line.split()[column_num-1]

# sample usage
print(find_line_and_column('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 4, 3))
</code>```

Alternatively, using the islice() function in itertools module would allow it to be done a little bit more succinctly:

```<code>import itertools

def find_line_and_column(filename, line_num, column_num):
    with open(filename, 'r') as file:
        line = next(itertools.islice(file, line_num-1, None), None) # get line_num-th line
        return line.split()[column_num-1]
</code>```

Body:
I am trying to parse out a string value from a certain column in a certain line in my ASCII file. Below I have included what I have tried to this point, the error I received when I ran this code is:

Attribute: 'list' object has no attribute 'split'`

Code:

import numpy as np
import matplotlib.pyplot as plt

f = open('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 'r')

line = f.readlines(49)
columns = line.split()
time = columns(2)
print (time)

f.close()

Body:
I would create a function to do it.

Note that line and column number are counted from 1, not zero.

def find_line_and_column(filename, line_num, column_num):
    with open(filename, 'r') as file:
        for i in range(line_num-1):  # skip over lines before the desired one
            next(file)
        line = next(file)  # read the desired line
        return line.split()[column_num-1]

# sample usage
print(find_line_and_column('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 4, 3))

Alternatively, using the islice() function in itertools module would allow it to be done a little bit more succinctly:

import itertools

def find_line_and_column(filename, line_num, column_num):
    with open(filename, 'r') as file:
        line = next(itertools.islice(file, line_num-1, None), None) # get line_num-th line
        return line.split()[column_num-1]


问:
Google Drive REST in iOS
My question is rather simple.
After integrating Google Drive REST API I could finally download files from my Google Drive.SO I have followed this example
https://developers.google.com/drive/v3/web/manage-downloads
Everything is working fine,and in console I get the information that the file is downloaded. So here is the question:where  it goes,to which folder ? What is the path to where the file is saved?
And how do I set the necessary save path if I need to save a file to iOS Documents folder?

```<code>NSString *fileId = @"0BwwA4oUTeiV1UVNwOHItT0xfa2M";

GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileId];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDataObject *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", file.data.length);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];
</code>```

I a developing for iOS 10 and an above and as I read the infrmation:NOTE: Because NSURLConnection is deprecated as of iOS 9 and OS X 10.11, this class has been superseded by GTMSessionFetcher.I should use either code provided by google(posted above ) or GTMSessionFetcher.I am using code from google.But Will be thankful is someone will help me solve my problem with both (google and GTMSessionFetcher) variants.

答:
UPD: For Google API Client lib

GTLRDataObject has data property which contains raw bytes of your file.  It is enough to safe your file using standard iOS methods.

There is also contentType property which is a string with MIME type of the file. You probably want to store this information somewhere along with the path to saved data, it will help you to properly display what kind of file (image/song/text) it is, as well as use it when you decode/open/read saved data to present actual information.

```<code>GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileId];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                 GTLRDataObject *file,
                                                 NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", file.data.length);

        // Here is where you take these bytes and save them as file to any location you want (typically your Documents folder)
        NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        [file.data writeToURL:documentsDirectoryURL atomically:YES];

        // Now you can store the url/path of the saved file somewhere along with the MIME type string (maybe new class or structure describing the file in your app)
        MyFile *file = [[MyFile alloc] initWithFilePath:[documentsDirectoryURL path] mimeType:contentType];
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];
</code>```

See CocoaDocs for GTLRDataObject reference.

Generic version: using iOS SDK

If you use NSURLSession, it has delegate method which you use to move file from temporary location to anywhere you need.

Obj-C

```<code>- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // Use `location` to move your data to Documents directory or wherever else
}
</code>```

Swift

```<code>func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // Use `location` to move your data to Documents directory or wherever else
}
</code>```

Title: Google Drive REST in iOS

Body:
My question is rather simple.
After integrating Google Drive REST API I could finally download files from my Google Drive.SO I have followed this example
https://developers.google.com/drive/v3/web/manage-downloads
Everything is working fine,and in console I get the information that the file is downloaded. So here is the question:where  it goes,to which folder ? What is the path to where the file is saved?
And how do I set the necessary save path if I need to save a file to iOS Documents folder?

NSString *fileId = @"0BwwA4oUTeiV1UVNwOHItT0xfa2M";

GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileId];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDataObject *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", file.data.length);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

I a developing for iOS 10 and an above and as I read the infrmation:NOTE: Because NSURLConnection is deprecated as of iOS 9 and OS X 10.11, this class has been superseded by GTMSessionFetcher.I should use either code provided by google(posted above ) or GTMSessionFetcher.I am using code from google.But Will be thankful is someone will help me solve my problem with both (google and GTMSessionFetcher) variants.

Body:
UPD: For Google API Client lib

GTLRDataObject has data property which contains raw bytes of your file.  It is enough to safe your file using standard iOS methods.

There is also contentType property which is a string with MIME type of the file. You probably want to store this information somewhere along with the path to saved data, it will help you to properly display what kind of file (image/song/text) it is, as well as use it when you decode/open/read saved data to present actual information.

GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileId];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                 GTLRDataObject *file,
                                                 NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", file.data.length);

        // Here is where you take these bytes and save them as file to any location you want (typically your Documents folder)
        NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        [file.data writeToURL:documentsDirectoryURL atomically:YES];

        // Now you can store the url/path of the saved file somewhere along with the MIME type string (maybe new class or structure describing the file in your app)
        MyFile *file = [[MyFile alloc] initWithFilePath:[documentsDirectoryURL path] mimeType:contentType];
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

See CocoaDocs for GTLRDataObject reference.

Generic version: using iOS SDK

If you use NSURLSession, it has delegate method which you use to move file from temporary location to anywhere you need.

Obj-C

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // Use `location` to move your data to Documents directory or wherever else
}

Swift

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // Use `location` to move your data to Documents directory or wherever else
}


问:
How to get google static map images with QT (C++)
I am trying to use QT to implement an application which download google static map images and show the map on a GUI application. In this way the local saved images can be used when there is no internet access.

I have checked a lot of example using QNetworkAccessManager, QNetworkRequest, QNetworkReply, but it will give back some information like "SSL handshake failed" and I am not able to download the image.

The url to download images is:

```<code>    urlbase = "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=%d&maptype=%s&size=%dx%d&format=jpg"
</code>```

Previous I used Python to do the work:

```<code>    result = urllib.urlopen(url).read()
    tile = PIL.Image.open(cStringIO.StringIO(result))
</code>```

which was very easy and convenient.

But when comes to QT and C++, it seems like all need a lot of self-built functions. So is there any easy way to do the job with C++ and QT?

答: Is there any compelling reason to use Qt network functionality? You can just stick the PIL image into a QGraphicsPixmapItem, and place that into a QGraphicsScene, which will get you the interactivity you want out of Qt.</p>

Body:
I am trying to use QT to implement an application which download google static map images and show the map on a GUI application. In this way the local saved images can be used when there is no internet access.

I have checked a lot of example using QNetworkAccessManager, QNetworkRequest, QNetworkReply, but it will give back some information like "SSL handshake failed" and I am not able to download the image.

The url to download images is:

    urlbase = "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=%d&maptype=%s&size=%dx%d&format=jpg"

Previous I used Python to do the work:

    result = urllib.urlopen(url).read()
    tile = PIL.Image.open(cStringIO.StringIO(result))

which was very easy and convenient.

But when comes to QT and C++, it seems like all need a lot of self-built functions. So is there any easy way to do the job with C++ and QT?


问:
What is the proper design pattern to manage the creation of many objects that have dependencies
I'm using PHP, and the Kohana framework, but that should be peripheral to this question.

I want to instantiate an object that has a couple related child objects, which in turn have some optional child objects that will be created.

I am new to OOP, and am trying to model the creation and management of this process.  I would like the process to be recoverable if a user doesn't finish it in one session, so I'm expecting to be able to serialize the object and pull it from the database.

My general direction so far:

From an admin panel select a link that reads www.example.com/create?new_process=true

That get request initializes the Creation_Management object.

Calls from the controller to the Creation_Management object:

```<code>$form_name = $creation_management_instance->which_form_to_render();

$this->view->set_file($file_name);
</code>```

The cycle then continues, with forms coming in and objects being completed until the process is done.

Is there a good way to structure this situation?

Let me know if I can be more clear anywhere.

答:
Well I don't know about the design pattern but it seems that you create a form and then depending upon certain conditions create the form's children.

Ideally, you would want to encapsulate the conditional creation of the children in the parent form. So pass your conditional parameters to the main form and that will decide which children it needs to construct and so on.

You will then need to serialize only one object (the main form), and the children will follow :)

Hope I got your use case right.

Body:
I'm using PHP, and the Kohana framework, but that should be peripheral to this question.

I want to instantiate an object that has a couple related child objects, which in turn have some optional child objects that will be created.

I am new to OOP, and am trying to model the creation and management of this process.  I would like the process to be recoverable if a user doesn't finish it in one session, so I'm expecting to be able to serialize the object and pull it from the database.

My general direction so far:

From an admin panel select a link that reads www.example.com/create?new_process=true

That get request initializes the Creation_Management object.

Calls from the controller to the Creation_Management object:

$form_name = $creation_management_instance->which_form_to_render();

$this->view->set_file($file_name);

The cycle then continues, with forms coming in and objects being completed until the process is done.

Is there a good way to structure this situation?

Let me know if I can be more clear anywhere.


问:
Array.prototype method with 'undefined' Output in Javascript
I don't understand why is the output is 'undefined'?

```<code>    JSON.stringify(a.maxKey())
</code>```

The output is still the same even if it is used like in the above.

        Array.prototype.maxKey = function (){
         Math.max.apply(Math,
           this.map(
             function(item){
               return item.key}
           )
         )
        }

        var a = [{key:1}, {key:2}]
        alert(a.maxKey())```

答:
You miss return keyword.

Array.prototype.maxKey = function() {
  return Math.max.apply(Math, this.map(item => item.key));
}

var a = [{ key: 1}, { key: 2}];
console.log(a.maxKey())```

Body:
I don't understand why is the output is 'undefined'?

    JSON.stringify(a.maxKey())

The output is still the same even if it is used like in the above.

        Array.prototype.maxKey = function (){
         Math.max.apply(Math,
           this.map(
             function(item){
               return item.key}
           )
         )
        }

        var a = [{key:1}, {key:2}]
        alert(a.maxKey())