问:
Xamarin forms contentpresenter goes in wrong row and empty on phone
I'm having a go at Xamarin Forms trying to create my custom 'GroupBox' control which is a just a grid with two rows. The first row should just show a box with a header . The header has a background rectangle with a label. The second row shows the content via ContentPresenter the content goes below in the second row.

I believe I've done the XAML correctly, this is how I'd do it in WPF, it shows in the GroupBox.xaml Forms Previewer fine, but when I add it into the main page, the content of the Groupbox goes into the first row (the header) instead of the second for some reason within the Previewer.

furthermore, when I attempt to run on an android phone, it just looks like this:

the group boxes are blank frames with no background colour or text

This is the code of the GroupBox 'user  control'

```<code><?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XForms.GroupBox">

    <Grid.RowDefinitions>
        <RowDefinition Height="0.2*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>

    <Frame Grid.Row="0" Grid.RowSpan="2" Margin="1" OutlineColor="AliceBlue"/>

    <BoxView Grid.Row="0" BackgroundColor="Red" Margin="1"/>

    <Label Grid.Row="0" TextColor="White" Text="Label!" Margin="2" />

    <Grid Grid.Row="1">
        <ContentPresenter/>
    </Grid>

</Grid>
</code>```

This code is in the main form:

```<code><?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:XForms;assembly=XForms"
                 x:Class="XForms.MainPage">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>
            <Grid Grid.Column="0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>

                <local:GroupBox Grid.Row="0">
                    <Label Text="I'm some content 1"/>
                </local:GroupBox>

                <local:GroupBox Grid.Row="1">
                    <Label Text="I'm some content 2"/>
                </local:GroupBox>

                <local:GroupBox Grid.Row="2">
                    <Label Text="I'm some content 3"/>
                </local:GroupBox>
            </Grid>
        </Grid>
    </ContentPage>
</code>```

in the main page XAML I can add a grid row to the label, even though there is no grid in the content, and it will work in the previewer -- but it's still blank on the phone (Which is most important).

```<code>  <local:GroupBox Grid.Row="0">
                    <Label Text="I'm some content 1" Grid.Row="1"/>
                </local:GroupBox>
</code>```

答:
I don't know what is the Frame for, but it is currently covering the BoxView and labels and thus made them invisible. Comment out the Frame and you will see the labels and BoxView again.

I believe I've done the XAML correctly, this is how I'd do it in WPF, it shows in the GroupBox.xaml Forms Previewer fine, but when I add it into the main page, the content of the Groupbox goes into the first row (the header) instead of the second for some reason within the Previewer.

ContentPresenter doesn't work like that.In Xamarin.Forms, it is generally used in ControlTemplate. For usage of ContentPresenter, please refer to this blog.

In your case, if you want to ContentPresenter to work. Instead of using Grid for GroupBox, you can use ContentView for GroupBox like below:

```<code>[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GroupBox : ContentView
{
    public GroupBox()
    {
        InitializeComponent();
    }
}
</code>```

GroupBox.xaml:

```<code><ContentView xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Demo.GroupBox">
<ContentView.ControlTemplate>
    <ControlTemplate>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="0.2*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <!--<Frame Grid.Row="0" Grid.RowSpan="2" Margin="1" OutlineColor="AliceBlue"></Frame>-->
            <BoxView Grid.Row="0" BackgroundColor="Red" Margin="1"  />
            <Label Grid.Row="0" TextColor="White" Text="Label!" Margin="2" />
            <Grid Grid.Row="1">
                <ContentPresenter/>
            </Grid>
        </Grid>
    </ControlTemplate>
</ContentView.ControlTemplate>
</code>```

Body:
I'm having a go at Xamarin Forms trying to create my custom 'GroupBox' control which is a just a grid with two rows. The first row should just show a box with a header . The header has a background rectangle with a label. The second row shows the content via ContentPresenter the content goes below in the second row.

I believe I've done the XAML correctly, this is how I'd do it in WPF, it shows in the GroupBox.xaml Forms Previewer fine, but when I add it into the main page, the content of the Groupbox goes into the first row (the header) instead of the second for some reason within the Previewer.

furthermore, when I attempt to run on an android phone, it just looks like this:

the group boxes are blank frames with no background colour or text

This is the code of the GroupBox 'user  control'

<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XForms.GroupBox">

    <Grid.RowDefinitions>
        <RowDefinition Height="0.2*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>

    <Frame Grid.Row="0" Grid.RowSpan="2" Margin="1" OutlineColor="AliceBlue"/>

    <BoxView Grid.Row="0" BackgroundColor="Red" Margin="1"/>

    <Grid Grid.Row="1">
        <ContentPresenter/>
    </Grid>

</Grid>

This code is in the main form:

<?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:XForms;assembly=XForms"
                 x:Class="XForms.MainPage">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>
            <Grid Grid.Column="0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>

                <local:GroupBox Grid.Row="0">

                </local:GroupBox>

                <local:GroupBox Grid.Row="1">

                </local:GroupBox>

                <local:GroupBox Grid.Row="2">

                </local:GroupBox>
            </Grid>
        </Grid>
    </ContentPage>

in the main page XAML I can add a grid row to the label, even though there is no grid in the content, and it will work in the previewer -- but it's still blank on the phone (Which is most important).

  <local:GroupBox Grid.Row="0">

                </local:GroupBox>

Body:
I don't know what is the Frame for, but it is currently covering the BoxView and labels and thus made them invisible. Comment out the Frame and you will see the labels and BoxView again.

I believe I've done the XAML correctly, this is how I'd do it in WPF, it shows in the GroupBox.xaml Forms Previewer fine, but when I add it into the main page, the content of the Groupbox goes into the first row (the header) instead of the second for some reason within the Previewer.

ContentPresenter doesn't work like that.In Xamarin.Forms, it is generally used in ControlTemplate. For usage of ContentPresenter, please refer to this blog.

In your case, if you want to ContentPresenter to work. Instead of using Grid for GroupBox, you can use ContentView for GroupBox like below:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GroupBox : ContentView
{
    public GroupBox()
    {
        InitializeComponent();
    }
}

GroupBox.xaml:

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Demo.GroupBox">
<ContentView.ControlTemplate>
    <ControlTemplate>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="0.2*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <!--<Frame Grid.Row="0" Grid.RowSpan="2" Margin="1" OutlineColor="AliceBlue"></Frame>-->
            <BoxView Grid.Row="0" BackgroundColor="Red" Margin="1"  />
            <Label Grid.Row="0" TextColor="White" Text="Label!" Margin="2" />
            <Grid Grid.Row="1">
                <ContentPresenter/>
            </Grid>
        </Grid>
    </ControlTemplate>
</ContentView.ControlTemplate>


来源: stackexchange

问:
EF Database context not saving update
I have some simple code I am using to update a profile picture that is saved in my database as a byte[]. For some odd reason it runs through my code with no errors at all but the database is not updated with the new picture that the user has chosen.

```<code>Client client = db.Clients.FirstOrDefault(c => c.Email == User.Identity.Name);
if (client != null)
{
    client.ProfileImage = bytes;
    db.Clients.Attach(client);
    var entry = db.Entry(client);
    entry.Property(e => e.ProfileImage).IsModified = true;
    db.SaveChanges();
}
</code>```

Here is the code for the Client entity class:

```<code>public partial class Client
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Client()
    {
        Customers = new HashSet<Customer>();
    }

    public int ID { get; set; }

    public int? StripeID { get; set; }

    [Required]
    [StringLength(200)]
    public string Name { get; set; }

    [Required]
    [StringLength(150)]
    public string Email { get; set; }

    public Guid UserID { get; set; }

    public bool IsActive { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public byte[] ProfileImage { get; set; }

    public virtual StripeInfo StripeInfo { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Customer> Customers { get; set; }
}
</code>```

Also after debugging the code I can see that the profile image is being set to the correct byte[] and the client.ProfileImage then contains the correct byte[], but as soon as db.SaveChanges() is called, client.ProfileImage is immediately set back to what it originally was. No errors occur or anything so I really can't figure out why this would be happening.

7/4/2017

Here are some additional things I have tried after looking on the internet some more:

1) Create a new database context instance to make the update.
2) Dispose of the original database context and create a new one to make the update.

Neither of the above attempts have worked. The ProfileImage property is still just set back to the original value when db.SaveChanges() is called.

答:
The issue is that the ProfileImage property of your entity has an attribute applied to it:

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
</code>```

Which, from the documentation, is telling Entity Framework:

Computed: The database generates a value when a row is inserted or updated.

You just need to remove that attribute completely.

ContentLicense: CC BY-SA 3.0

Title: EF Database context not saving update

Body:
I have some simple code I am using to update a profile picture that is saved in my database as a byte[]. For some odd reason it runs through my code with no errors at all but the database is not updated with the new picture that the user has chosen.

Client client = db.Clients.FirstOrDefault(c => c.Email == User.Identity.Name);
if (client != null)
{
    client.ProfileImage = bytes;
    db.Clients.Attach(client);
    var entry = db.Entry(client);
    entry.Property(e => e.ProfileImage).IsModified = true;
    db.SaveChanges();
}

Here is the code for the Client entity class:

public partial class Client
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Client()
    {
        Customers = new HashSet<Customer>();
    }

    public int ID { get; set; }

    public int? StripeID { get; set; }

    [Required]
    [StringLength(200)]
    public string Name { get; set; }

    [Required]
    [StringLength(150)]
    public string Email { get; set; }

    public Guid UserID { get; set; }

    public bool IsActive { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public byte[] ProfileImage { get; set; }

    public virtual StripeInfo StripeInfo { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Customer> Customers { get; set; }
}

Also after debugging the code I can see that the profile image is being set to the correct byte[] and the client.ProfileImage then contains the correct byte[], but as soon as db.SaveChanges() is called, client.ProfileImage is immediately set back to what it originally was. No errors occur or anything so I really can't figure out why this would be happening.

7/4/2017

Here are some additional things I have tried after looking on the internet some more:

1) Create a new database context instance to make the update.
2) Dispose of the original database context and create a new one to make the update.

Neither of the above attempts have worked. The ProfileImage property is still just set back to the original value when db.SaveChanges() is called.

Body:
The issue is that the ProfileImage property of your entity has an attribute applied to it:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

Which, from the documentation, is telling Entity Framework:

Computed: The database generates a value when a row is inserted or updated.

You just need to remove that attribute completely.


问:
Zip operator in RxJava is not working with Retrofit
I am trying to use zip operator in RxJava in android, where I am trying to execute 3 parallel API Calls to get their result together. But my zip operator is not producing result. The code for my sample problem is as follows:

Code for my gradle file

```<code>compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
</code>```

I have also included this in my gradle file

```<code>exclude 'META-INF/rxjava.properties'
</code>```

Code for my Retrofit Client

```<code>retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .addConverterFactory(GsonConverterFactory.create())
    .client(client).build();
</code>```

Code for my API Interface

```<code>public interface ApiInterface {
    @GET("/users/{UUID}/count.json")
    Observable<Count> getCountInfo(@Path("UUID") String UUID, @Query("store_id") String sort);
    @GET("v1/users/{UUID}.json")
    Observable<GetStatus> getState(@Path("UUID") String UUID);
    @GET("v1/user/{UUID}/points.json")
    Observable<Response> getResponse(@Path("UUID") String UUID);
}
</code>```

Code for my Observables is

```<code>Retrofit repo = APIClient.getClient(baseUrl);
Observable<Count> userObservable = repo.create(ApiInterface.class)
    .getCount(userid,"1")
    .subscribeOn(Schedulers.newThread())
    .observeOn(Schedulers.io());
Observable<GetStatus> eventObservable = APIClient.getClient(baseUrl)
    .create(ApiInterface.class)
    .getState(userid)
    .subscribeOn(Schedulers.newThread())
    .observeOn(Schedulers.io());
Observable<Response> eventsObservable1 = APIClient
    .getClient(baseUrl)
    .create(ApiInterface.class)
    .getPoints(userid)
    .subscribeOn(Schedulers.newThread())
    .observeOn(Schedulers.io());
</code>```

Code for my combined observable and zip operator is:

```<code>Observable<CommonSplashResponse> combined = Observable.zip(userObservable, eventsObservable, eventsObservable1,
new Func3<Count, GetStatus, Response, CommonResponse>() {
    @Override
    public CommonResponse call(Count count, GetStatus uStatus,
        Response lResponse) {
        return new CommonResponse(count, uStatus, lResponse);
    }
});
combined.subscribe(new Subscriber<CommonSplashResponse>() {
    @Override
    public void onCompleted() {
    }
    @Override
    public void onError(Throwable e) {
    }
    @Override
    public void onNext(CommonResponse o) {
        LOG.info("Count Value is " + o.getCount());
        /**
        ***
        */
    }
});
</code>```

The problem I am facing is that, the statements inside the onNext of the Combined Observable are not being executed.
What could be the reason for glitch in execution?
So I wanted to ask:

Is there any issue in my dependencies?

Should AndroidSchedulers.mainThread() be used instead of Schedulers.io()

答:
For the .zip() operator to emit anything, all zipped observables have to emit at least once. If one of your observables emits an error, or does not emit at all, you will never receive an onNext event.

For checking for error emissions, add logging or breakpoints into your onError within subscribe

For checking for missing emissions, you can add doOnNext and doOnCompleted calls with logging after all your zipped Observables and see which one does not emit

Cheers!

Body:
I am trying to use zip operator in RxJava in android, where I am trying to execute 3 parallel API Calls to get their result together. But my zip operator is not producing result. The code for my sample problem is as follows:

Code for my gradle file

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

I have also included this in my gradle file

exclude 'META-INF/rxjava.properties'

Code for my Retrofit Client

retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .addConverterFactory(GsonConverterFactory.create())
    .client(client).build();

Code for my API Interface

public interface ApiInterface {
    @GET("/users/{UUID}/count.json")
    Observable<Count> getCountInfo(@Path("UUID") String UUID, @Query("store_id") String sort);
    @GET("v1/users/{UUID}.json")
    Observable<GetStatus> getState(@Path("UUID") String UUID);
    @GET("v1/user/{UUID}/points.json")
    Observable<Response> getResponse(@Path("UUID") String UUID);
}

Code for my Observables is

Retrofit repo = APIClient.getClient(baseUrl);
Observable<Count> userObservable = repo.create(ApiInterface.class)
    .getCount(userid,"1")
    .subscribeOn(Schedulers.newThread())
    .observeOn(Schedulers.io());
Observable<GetStatus> eventObservable = APIClient.getClient(baseUrl)
    .create(ApiInterface.class)
    .getState(userid)
    .subscribeOn(Schedulers.newThread())
    .observeOn(Schedulers.io());
Observable<Response> eventsObservable1 = APIClient
    .getClient(baseUrl)
    .create(ApiInterface.class)
    .getPoints(userid)
    .subscribeOn(Schedulers.newThread())
    .observeOn(Schedulers.io());

Code for my combined observable and zip operator is:

Observable<CommonSplashResponse> combined = Observable.zip(userObservable, eventsObservable, eventsObservable1,
new Func3<Count, GetStatus, Response, CommonResponse>() {
    @Override
    public CommonResponse call(Count count, GetStatus uStatus,
        Response lResponse) {
        return new CommonResponse(count, uStatus, lResponse);
    }
});
combined.subscribe(new Subscriber<CommonSplashResponse>() {
    @Override
    public void onCompleted() {
    }
    @Override
    public void onError(Throwable e) {
    }
    @Override
    public void onNext(CommonResponse o) {
        LOG.info("Count Value is " + o.getCount());
        /**
        ***
        */
    }
});

The problem I am facing is that, the statements inside the onNext of the Combined Observable are not being executed.
What could be the reason for glitch in execution?
So I wanted to ask:

Is there any issue in my dependencies?

Should AndroidSchedulers.mainThread() be used instead of Schedulers.io()


问:
Maven resource filtering exclude
I have a following maven configuration:

```<code>        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>keystore.jks</exclude>
                </excludes>
            </resource>
        </resources>
</code>```

I want keystore.jks to be included in my classes/war application but not to be processed by Maven filtering.

How to change this configuration ?

答:
Binary filtering</p>

```<code><plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-resources-plugin</artifactId>
  <version>3.0.2</version>
  <configuration>
    <nonFilteredFileExtensions>
      <nonFilteredFileExtension>jks</nonFilteredFileExtension>
    </nonFilteredFileExtensions>
  </configuration>
</plugin>
</code>```

Title: Maven resource filtering exclude

Body:
I have a following maven configuration:

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>keystore.jks</exclude>
                </excludes>
            </resource>
        </resources>

I want keystore.jks to be included in my classes/war application but not to be processed by Maven filtering.

How to change this configuration ?

Body:
Binary filtering

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-resources-plugin</artifactId>
  <version>3.0.2</version>
  <configuration>
    <nonFilteredFileExtensions>
      <nonFilteredFileExtension>jks</nonFilteredFileExtension>
    </nonFilteredFileExtensions>
  </configuration>
</plugin>


问:
Identifying which element invoked the event
I have following html code

```<code><input type="button"  id ="b1" value="Click me" onclick="msg()" />
<input type="button" id="b2"   value="Click me" onclick="msg()" />
</code>```

now in my javascript i want to identify whether button one was clicked or button 2. How can i do it?

答:
From reading answers/comments I find that you're using dojo. You could reference it via the event object. I've only tested this in chrome,FF, and ie8 but this seemed to work:

```<code>templateString: "<div>" + '<button id="button1" dojoAttachEvent="onclick: msg">press me1</button><button id="button2" dojoAttachEvent="onclick: msg">press me2</button></div>',
msg:function(e){
    alert(e.currentTarget.id);
}
</code>```

Live example

ContentLicense: CC BY-SA 2.5

Body:
I have following html code

<input type="button"  id ="b1" value="Click me" onclick="msg()" />
<input type="button" id="b2"   value="Click me" onclick="msg()" />

now in my javascript i want to identify whether button one was clicked or button 2. How can i do it?

Body:
From reading answers/comments I find that you're using dojo. You could reference it via the event object. I've only tested this in chrome,FF, and ie8 but this seemed to work:

templateString: "<div>" + '<button id="button1" dojoAttachEvent="onclick: msg">press me1</button><button id="button2" dojoAttachEvent="onclick: msg">press me2</button></div>',
msg:function(e){
    alert(e.currentTarget.id);
}

Live example


问:
How to send All objects of Mutable Array to Another Class?
I want to send Mutable Array with all its objects from my First Class to Second Class. I have no idea how can i do this please anybody tell me the way... </p>

答:
you make one declare mutable array and make it property on other class where you want to then just give like follow

vc.nsmutablearray = the_array_you_want_to_send;


问:
How to open multiple pics on single button
I made four buttons with single bootstrap modal & a button in bootstrap modal to open pic according to click on four buttons.

Now single bootstrap modal is open on each button click & one button inside modal ("Open Document") I want to work on that like...

If anyone open modal through Open Modal2 then on click "open document" should be open pic as per modal 2

I'm unable to do this anyone can do it?

.buttons{ margin:20px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="buttons">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Moda2</button>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Moda3</button>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Moda4</button>
</div>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
<button class="btn btn-success" onClick="window.open('https://i.stack.imgur.com/SdR1m.jpg','_self')">Open Document</button>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div></code>```

enter image description here

答:
Here is your Solution mate :

$(".modelButton").click(function(){
  $(".modelDocButton").attr("href",$(this).data("href"));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.buttons{ margin:20px;}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <button type="button" class="btn btn-info btn-lg modelButton" data-toggle="modal" data-target="#myModal" data-href="https://i.stack.imgur.com/SdR1m.jpg">Open Modal</button>
    <button type="button" class="btn btn-info btn-lg modelButton" data-toggle="modal" data-target="#myModal" data-href="https://i.imgur.com/3TWgv.jpg">Open Moda2</button>

            <button type="button" class="close" data-dismiss="modal">×</button>

Modal 1

    Open Document

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

    ```
</div>
</div>
</p>

```

            <button type="button" class="close" data-dismiss="modal">×</button>

Modal 2

    <button class="btn btn-success" onClick="window.open('https://i.stack.imgur.com/SdR1m.jpg','_self')">Open Document</button>

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

```

ContentLicense: CC BY-SA 4.0

Body:
I made four buttons with single bootstrap modal & a button in bootstrap modal to open pic according to click on four buttons.

Now single bootstrap modal is open on each button click & one button inside modal ("Open Document") I want to work on that like...

If anyone open modal through Open Modal2 then on click "open document" should be open pic as per modal 2

I'm unable to do this anyone can do it?

.buttons{ margin:20px;}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Moda2</button>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Moda3</button>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Moda4</button>

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

<button class="btn btn-success" onClick="window.open('https://i.stack.imgur.com/SdR1m.jpg','_self')">Open Document</button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

enter image description here

Body:
Here is your Solution mate :

$(".modelButton").click(function(){
  $(".modelDocButton").attr("href",$(this).data("href"));
});

.buttons{ margin:20px;}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="buttons">
    <button type="button" class="btn btn-info btn-lg modelButton" data-toggle="modal" data-target="#myModal" data-href="https://i.stack.imgur.com/SdR1m.jpg">Open Modal</button>
    <button type="button" class="btn btn-info btn-lg modelButton" data-toggle="modal" data-target="#myModal" data-href="https://i.imgur.com/3TWgv.jpg">Open Moda2</button>

    </div>

    <!-- Modal -->
    <div id="myModal" class="modal fade" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Modal 1</h4>
          </div>
          <div class="modal-body">
    <a class="btn btn-success modelDocButton" href="#">Open Document</a>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>

      </div>
    </div>

 <!-- Modal -->
    <div id="myModal2" class="modal fade" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Modal 2</h4>
          </div>
          <div class="modal-body">
    <button class="btn btn-success" onClick="window.open('https://i.stack.imgur.com/SdR1m.jpg','_self')">Open Document</button>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>

      </div>
    </div>

<!-- end snippet -->


问:
cc -switch (or other "automatic" mechanism) to keep functions static within modules
I have two formerly stand-alone modules, say this.c and that.c, that I now want to compile together as cc this.c that.c -o whatever   Don't worry about just one main(), etc; that's all been taken care of, and everything would work okay except for the following...

Each module contains several dozen (maybe in all 50) "duplicate" functions; same names but slightly different behaviors. And I never bothered declaring them static. I started editing in that keyword, which would be lengthy-but-doable by itself. Unfortunately, I've also declared each function in every other function that calls it, so I have to edit both every function's entry point itself, as well as every function that calls any other functions. So now that's a cumbersome mess.

And please don't admonish me that the modules are too big, blah, blah, blah. Yeah, it's a mess of my own making. But my time machine's in the shop, so there's no use belaboring that point.

What I'd like to find (but can't) is some cc -switch that says something to the effect, -automatically-treat-all-functions-static-in-their-own-modules Or something like that. So, Question: is there any way to accomplish this without exhaustively editing pretty much everything everywhere?

(P.S. Other kinds of solutions do work, e.g., I can compile them separately and have the "main" one popen() the other one and read its output. But that makes for a cumbersome user-installation-experience which I'd like to avoid. So compiling them together is the only solution I can think of that keeps all the "internals" internal.)

答:
If you have 2 functions with the same name but in different module, you have to use static keyword on both otherwise you will confuse linker when linking objects together.

So, there is no way to automatically do this for you.

Good practice is that every function which is private inside module should be declared as static to prevent problems you have.

If modules are between totally different (one module does not have any dependancy to another) then there is no problem at all unless you have functions with public use with the same name from both modules.

```<code>//This approach is OK
that.c:
static int myfunc(void) {
    return 5;
}

this.c:
static int myfunc(void) {
     return 6;
}
</code>```

These 2 functions are totally different and are visible only inside your module.

Body:
If you have 2 functions with the same name but in different module, you have to use static keyword on both otherwise you will confuse linker when linking objects together.

So, there is no way to automatically do this for you.

Good practice is that every function which is private inside module should be declared as static to prevent problems you have.

If modules are between totally different (one module does not have any dependancy to another) then there is no problem at all unless you have functions with public use with the same name from both modules.

//This approach is OK
that.c:
static int myfunc(void) {
    return 5;
}

this.c:
static int myfunc(void) {
     return 6;
}

These 2 functions are totally different and are visible only inside your module.


问:
finditemsinebaystores returns items not for my store
I send a request xml to find items in my store that has any custom labels set for the seller. But ebay returns a response with a lot of items that not are in my store.
How can I do that?

That's my code:

```<code>$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';
self::get_cvs_array();
$xmlrequest;
$xml_filters = "";
$a = 1;
while ($a < count($this->cvs_array)) {
    $xml_filters .="<itemFilter>\n<name>Custom Label</name>\n<value>".$this->cvs_array[$a][0]."</value>\n</itemFilter>\n";
    $a += 1;
}
// Create the XML request to be POSTed
$xmlrequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xmlrequest .= "<findItemsIneBayStoresRequest xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
$xmlrequest .= "<storeName>myStoreName</storeName>\n";
$xmlrequest .= $xml_filters;
$xmlrequest .= "</findItemsIneBayStoresRequest>";

// Set up the HTTP headers
$headers = array(
'X-EBAY-SOA-SERVICE-NAME: FindingService',
'X-EBAY-SOA-OPERATION-NAME: findItemsIneBayStores',
'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
'X-EBAY-SOA-GLOBAL-ID: EBAY-ES',
'X-EBAY-SOA-SECURITY-APPNAME: $myAppId',
'Content-Type: text/xml;charset=utf-8',
);

$session  = curl_init($endpoint);                       // create a curl session
curl_setopt($session, CURLOPT_POST, true);              // POST request type
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    // set headers using $headers array
curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    // return values as a string, not to std out

$responsexml = curl_exec($session);                     // send the request
curl_close($session);
</code>```

答:
The findItemsIneBayStores is for finding items from sellers that have stores.

To get your own items, you should use GetMyeBaySelling instead.

In this call, you can use

```<code><ActiveList>
    <Include>true</Include>
</ActiveList>
</code>```

to get only your Active List (will not include the Sold, Unsold, etc.).
You will find all the documentation needed here

Body:
I send a request xml to find items in my store that has any custom labels set for the seller. But ebay returns a response with a lot of items that not are in my store.
How can I do that?

That's my code:

$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';
self::get_cvs_array();
$xmlrequest;
$xml_filters = "";
$a = 1;
while ($a < count($this->cvs_array)) {
    $xml_filters .="<itemFilter>\n<name>Custom Label</name>\n<value>".$this->cvs_array[$a][0]."</value>\n</itemFilter>\n";
    $a += 1;
}
// Create the XML request to be POSTed
$xmlrequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xmlrequest .= "<findItemsIneBayStoresRequest xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
$xmlrequest .= "<storeName>myStoreName</storeName>\n";
$xmlrequest .= $xml_filters;
$xmlrequest .= "</findItemsIneBayStoresRequest>";

// Set up the HTTP headers
$headers = array(
'X-EBAY-SOA-SERVICE-NAME: FindingService',
'X-EBAY-SOA-OPERATION-NAME: findItemsIneBayStores',
'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
'X-EBAY-SOA-GLOBAL-ID: EBAY-ES',
'X-EBAY-SOA-SECURITY-APPNAME: $myAppId',
'Content-Type: text/xml;charset=utf-8',
);

$session  = curl_init($endpoint);                       // create a curl session
curl_setopt($session, CURLOPT_POST, true);              // POST request type
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    // set headers using $headers array
curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    // return values as a string, not to std out

$responsexml = curl_exec($session);                     // send the request
curl_close($session);

Body:
The findItemsIneBayStores is for finding items from sellers that have stores.

To get your own items, you should use GetMyeBaySelling instead.

In this call, you can use

<ActiveList>
    <Include>true</Include>
</ActiveList>

to get only your Active List (will not include the Sold, Unsold, etc.).
You will find all the documentation needed here


问:
Check if ALL elements of list A within list B
I have done my research, however all these techniques return true, i need them to return false.

```<code>print set([2, 2]).issubset([2, 3, 3]) #returns True
print set([2, 3, 3]).issuperset(set([2, 2])) #returns True
print all(x in {2, 3, 3} for x in [2, 2]) #returns True
print set([2, 2]) <= set([2, 3, 3]) #returns True
</code>```

The lists I'm comparing have duplicate numbers

答: Just look for an implementation of a multiset. It should pass (most of) your test cases. </p>

Body:
I have done my research, however all these techniques return true, i need them to return false.

print set([2, 2]).issubset([2, 3, 3]) #returns True
print set([2, 3, 3]).issuperset(set([2, 2])) #returns True
print all(x in {2, 3, 3} for x in [2, 2]) #returns True
print set([2, 2]) <= set([2, 3, 3]) #returns True

The lists I'm comparing have duplicate numbers


问:
How to execute a command on server using Expect
I want to remotely delete a file/execute another script on my server. Manually this could be done by ssh-login -> cd /path/ -> rm somefiles -> . script.sh

I want to automatic this process. So that when I execute expect expectscript.sh port serverip user userpasswd, the script would do the whole process for me.

So I write the following script. Things go smoothly till the ssh-login process finished. I don't know what is wrong with the last 3 lines of the code. Could someone help?

```<code>#!/usr/bin/expect
set timeout 20
set port [lindex $argv 0]
set ip [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]
spawn ssh "$user\@$ip" "-p" "$port"
expect "password:"
send "$password\r"
spawn "cd /etc/abcd/"
spawn "rm -f efg/*"
spawn ". somescriptinefg.sh"
</code>```

答:
Change the spawn to send solve the problem~

Literally,

spawn "Creates a new process by running a given program."

send "Sends string to the current process."

Body:
I want to remotely delete a file/execute another script on my server. Manually this could be done by ssh-login -> cd /path/ -> rm somefiles -> . script.sh

I want to automatic this process. So that when I execute expect expectscript.sh port serverip user userpasswd, the script would do the whole process for me.

So I write the following script. Things go smoothly till the ssh-login process finished. I don't know what is wrong with the last 3 lines of the code. Could someone help?

#!/usr/bin/expect
set timeout 20
set port [lindex $argv 0]
set ip [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]
spawn ssh "$user\@$ip" "-p" "$port"
expect "password:"
send "$password\r"
spawn "cd /etc/abcd/"
spawn "rm -f efg/*"
spawn ". somescriptinefg.sh"


问:
Content model including a list of dates
I want to create a content model containing a list of dates of variable length. The only way I figured out how to do it is to create a new nested content model with one date field, and then include these single date entries as a reference list. The issue with this approach is that the date is not showing as the entry title. Instead, a list of dates is only displayed as a list of blocks all labeled "Untitled", which is very unintuitive, as shown in the following screenshot.

Screenshot of the current status

So the questions are: Is there a good way to display the date as Entry title, or is there another solution to include a list of dates into the content model?

I am investigating the use of UI Extensions to solve this, but maybe there is a simpler build-in solution to the problem, than a custom developed extension.

答: You can't specify the Entry title from date fields, but rather only from short or long text fields, so a UI extension would be the way to go. Add a short text field called title (and specify that this field represents the entry title) then create a UI extension which will put a string of the selected date from the date field into the title field. Check out https://github.com/contentful/extensions/tree/master/samples/slug for a good starting point.</p>

Title: Content model including a list of dates


答:
You can use list.count inside of the all function:

```<code>all(l1.count(i) <= l2.count(i) for i in set(l1))
</code>```

For every element in l1, this will check if there is at least as many ocurences in l2.
If any element of l1 appears fewer times in l2, then the all function will return False.
The conversion of l1 into a set prevents the number of iterations from increasing when l1 consists in a large number of the same value.

Test:

```<code>>>> f = lambda l1, l2: all(l1.count(i) <= l2.count(i) for i in set(l1))
>>> f([2, 2], [2, 3, 3])
False
>>> f([2, 2], [2, 2, 3])
True
</code>```

Title: Check if ALL elements of list A within list B

Body:
You can use list.count inside of the all function:

all(l1.count(i) <= l2.count(i) for i in set(l1))

For every element in l1, this will check if there is at least as many ocurences in l2.
If any element of l1 appears fewer times in l2, then the all function will return False.
The conversion of l1 into a set prevents the number of iterations from increasing when l1 consists in a large number of the same value.

Test:

>>> f = lambda l1, l2: all(l1.count(i) <= l2.count(i) for i in set(l1))
>>> f([2, 2], [2, 3, 3])
False
>>> f([2, 2], [2, 2, 3])
True


问:
SensorTag 2 CC2650 advertising indefinately firmware
I want to use a SensorTag 2 so that it is sitting there broadcasting it's data (and, critically connectable over bluetooth) from when it's turned on to when\if I ever turn it off. Out of the box, the tag is set to only advertise over Bluetooth for a few mins which means that when the connection eventually fails or when the device connected to the tag boots etc etc you can't connect again without physically visiting the tag and resetting it.

I see there is firmware that the myWeatherCenter people have created that lets the tag work as a weather station by basically setting it to advertise indefinitely... frustratingly though their firmware is only the sensortag version 1 :-(

I've researched on and off for months and months now and nothing coming back.. suggesting either nobody else wants this, there is a really simple solution everyone one else knows about or ...? I can't even see anyone else asking this question really... which is worrying.
Does anyone have a firmware file that sets this setting for the sensortag 2 or know how to modify the firmware to set this setting?

答: You could find the workflow for a complete solution and the firmware for continuous advertising which I created recently, at Sensortag CC2650STK Custom Firmware Modification&Download Workflow (Continuous Advertising) using Code Composer Studio, Debugger DevPack and Flash Programmer 2 software</p>


问:
JQuery Ajax POST in Codeigniter not working
i have a problem with jquery ajax post in codeigniter,
problem I faced is when the submit button is clicked , an error occurs

this is my code

home.js

```<code>form.on('submit', function(e){
    e.preventDefault();
    var fields = {};
    form.find('input','textarea').each(function(index, el){
        el.readOnly = true;
        fields[$(el).attr('name')] = $(el).val();
    });

    // send request to server
    $.ajax({
        type: 'POST',
        url: '/home/tryproduct/',
        data: fields,
        dataType: 'json'
    })
    .done(function(result){
        if(result.error === false){
            alert(result.message);
        } else {
            alert(result.message);
        }
        form.find('input','textarea').each(function(index, el){
            el.readOnly = false;
        });
        form[0].reset();
    });
});
</code>```

this is my view

```<code><form class="row" name="free-trial">
                    <div class="col-sm-6 col-xs-12">
                        <div class="form-group">
                            <button type="button" onclick="autoFillUsingLinkedin()" class="btn btn-linkedin btn-block">
                            <span class="icon icon-social-linkedin"></span>
                            Autofill Using LinkedIn
                            </button>
                        </div>
                    </div>
                    <div class="col-sm-6 col-xs-12"></div>
                    <div class="col-sm-6 col-xs-12">
                        <div class="form-group">
                            <label>Name</label>
                            <div class="row between-xs">
                                <input type="text"
                                    name="firstName" placeholder="First Name" class="form-control col-xs"  required=""/>
                                    <?php echo form_error('firstName'); ?>
                                <input type="text" name="lastName" placeholder="Last Name" class="form-control col-xs" required=""/>
                                <?php echo form_error('lastName'); ?>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Company</label>
                            <input type="text" name="company" placeholder="Your Current Company" class="form-control" required=""/>
                        </div>
                        <div class="form-group">
                            <label>Position</label>
                            <input type="text" name="position" placeholder="Position On Your Company" class="form-control" required=""/>
                        </div>
                        <div class="form-group">
                            <label>Address</label>
                            <input type="text" name="address" placeholder="JL. Jalan 12. Kota. Bandung" class="form-control" required=""/>
                        </div>
                    </div>
                    <div class="col-sm-6 col-xs-12">
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" name="email" placeholder="We Will Use This For Registration" class="form-control" required=""/>
                            <?php echo form_error('email'); ?>
                        </div>
                        <div class="form-group">
                            <label>Phone Number</label>
                            <input type="text" name="phone" placeholder="+(62) xxx" class="form-control" required=""/>
                        </div>
                        <div class="form-group">
                            <label>Notes</label>
                            <textarea type="text" name="notes" placeholder="Tell Us What You Want" rows="4" class="form-control" required=""></textarea>
                        </div>
                    </div>
                    <div class="col-sm-6 col-xs-12">
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary btn-block">
                            <span class="icon icon-paper-airplane"></span>
                            SUBMIT FOR FREE TRIAL
                            </button>
                        </div>
                    </div>
                </form>
</code>```

Controller

```<code>public function tryproduct(){
    $this->view = FALSE;
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
    $data = array(
        'firstname' => $this->input->post('firstname'),
        'lastname'  => $this->input->post('lastname'),
        'position'  => $this->input->post('position'),
        'company'   => $this->input->post('company'),
        'address'   => $this->input->post('address'),
        'phone'     => $this->input->post('phone'),
        'email'     => $this->input->post('email'),
        'notes'     => $this->input->post('notes')
    );
    $id = $this->trial_request->insert($data);
    if(!$id){
        echo json_encode(array(
            'error' => true,
            'message' => 'error register product trial'
        ));
    } else {
        echo json_encode(array(
            'error' => false,
            'message' => 'success register product trial',
            'user' => $data,
        ));
    }
}
</code>```

thanks before guys

答: try to set FALSE csrf_protection in config.php. If you want set it TRUE, make it sure you change <form action=....> to form_open()

Body:
i have a problem with jquery ajax post in codeigniter,
problem I faced is when the submit button is clicked , an error occurs

this is my code

home.js

form.on('submit', function(e){
    e.preventDefault();
    var fields = {};
    form.find('input','textarea').each(function(index, el){
        el.readOnly = true;
        fields[$(el).attr('name')] = $(el).val();
    });

    // send request to server
    $.ajax({
        type: 'POST',
        url: '/home/tryproduct/',
        data: fields,
        dataType: 'json'
    })
    .done(function(result){
        if(result.error === false){
            alert(result.message);
        } else {
            alert(result.message);
        }
        form.find('input','textarea').each(function(index, el){
            el.readOnly = false;
        });
        form[0].reset();
    });
});

this is my view

<form class="row" name="free-trial">

                            <button type="button" onclick="autoFillUsingLinkedin()" class="btn btn-linkedin btn-block">

                            Autofill Using LinkedIn
                            </button>

                            Name

                                <input type="text"
                                    name="firstName" placeholder="First Name" class="form-control col-xs"  required=""/>
                                    <?php echo form_error('firstName'); ?>
                                <input type="text" name="lastName" placeholder="Last Name" class="form-control col-xs" required=""/>
                                <?php echo form_error('lastName'); ?>

                            Company
                            <input type="text" name="company" placeholder="Your Current Company" class="form-control" required=""/>

                            Position
                            <input type="text" name="position" placeholder="Position On Your Company" class="form-control" required=""/>

                            Address
                            <input type="text" name="address" placeholder="JL. Jalan 12. Kota. Bandung" class="form-control" required=""/>

                            Email
                            <input type="email" name="email" placeholder="We Will Use This For Registration" class="form-control" required=""/>
                            <?php echo form_error('email'); ?>

                            Phone Number
                            <input type="text" name="phone" placeholder="+(62) xxx" class="form-control" required=""/>

                            Notes
                            <textarea type="text" name="notes" placeholder="Tell Us What You Want" rows="4" class="form-control" required=""></textarea>

                            <button type="submit" class="btn btn-primary btn-block">

                            SUBMIT FOR FREE TRIAL
                            </button>

                </form>

Controller

public function tryproduct(){
    $this->view = FALSE;
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
    $data = array(
        'firstname' => $this->input->post('firstname'),
        'lastname'  => $this->input->post('lastname'),
        'position'  => $this->input->post('position'),
        'company'   => $this->input->post('company'),
        'address'   => $this->input->post('address'),
        'phone'     => $this->input->post('phone'),
        'email'     => $this->input->post('email'),
        'notes'     => $this->input->post('notes')
    );
    $id = $this->trial_request->insert($data);
    if(!$id){
        echo json_encode(array(
            'error' => true,
            'message' => 'error register product trial'
        ));
    } else {
        echo json_encode(array(
            'error' => false,
            'message' => 'success register product trial',
            'user' => $data,
        ));
    }
}

thanks before guys


问:
Convert Thread.Join(timeLapse) to equivalent non-thread pattern
I have the following code:

```<code>Thread validationThread = new Thread(DoAsyncValidationMethod);

validationThread.Start(threadParams);

bool isAborted = false;

int timeLeft = 5000;

// wait for thread terminates itself
if (!validationThread.Join(timeLeft))
{
    // timeout, abort thread
    validationThread.Abort();
    isAborted = true;
}
</code>```

In other words, I'm doing some work that is supposed to complete in the time lapse specified (5000 ms). If completed or not, the thread approach taken will guarantee the code returns no later than 5 sec after it started.

Is there a way to accomplish this with the async/await pattern? or since the thread is just used for the trick, is there any other approach to take?

The more elegant and simple, the better.
Thank you for the help.

答:
Use a CancellationTokenSource. The source is a factory for CancellationTokens. You pass this token on to everyone you want to be able to cancel its processing in a neat way. When you want to cancel all processes that has a CancellationToken from the same CancellationTokenSource, just tell the CancellationTokenSource to send a cancel to all CancellationTokens it producted, thus cancelling all processes that have tokens from this source.

And the nice thing is, a CancellationTokenSource has a CancelAfter(some timeout).

Its good practice, to let your process starter give you the cancellationToken, so your process starter can decide which processes it wants to cancel in one call.

```<code>public async Task<MyResult> MyProcessAsync(CancellationToken cancellationToken, ...)
{
    // do something lengthy processing, without await, regularly check if Cancellation requested
    while (stillProcessing)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ... // process
    }

    // do some processing with async-await:
    await myDbContext.SaveChangesAsync(cancellationToken);
}
</code>```

Usage:

```<code>private async Task LengthyProcessing(...)
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    tokenSource.CancelAfter(TimeSpan.FromSeconds(5));

    CancellationToken myCancellationToken = tokenSource.Token
    try
    {
       // Start one task, don't await yet:
       var myTask = await MyProcessAsync(myCancellationToken, ...)
       // during processing there will be regular check if cancellation requested
       // meanwhile, whenever myTask has to await, I can do some processing
       // I'll have to check for cancellation regularly also:

       while(...)
       {
           myCancellationToken.ThrowIfCancellationRequested();
           DoSomeProcessing();
           ...
       }

       MyResult result = await myTask;
       // if here, not cancelled. can use Result:
       ProcessResult(result);
    }
    catch (OperationCanceledException exc)
    {
        ProcessOperationCanceled();
    }
}
</code>```

Note that only one CancelltionTokenSource is used. Whenever this source thinks that something should be cancelled, all threads that have tokens from this source get notified about the cancellationrequest.

Instead of using exception handling via CancellationToken.ThrowIfCancellationRequested() consider using bool CancellationToken.IsCancellationRequested.

MSDN how to cancel a task and its children

Body:
I have the following code:

Thread validationThread = new Thread(DoAsyncValidationMethod);

validationThread.Start(threadParams);

bool isAborted = false;

int timeLeft = 5000;

// wait for thread terminates itself
if (!validationThread.Join(timeLeft))
{
    // timeout, abort thread
    validationThread.Abort();
    isAborted = true;
}

In other words, I'm doing some work that is supposed to complete in the time lapse specified (5000 ms). If completed or not, the thread approach taken will guarantee the code returns no later than 5 sec after it started.

Is there a way to accomplish this with the async/await pattern? or since the thread is just used for the trick, is there any other approach to take?

The more elegant and simple, the better.
Thank you for the help.

Body:
Use a CancellationTokenSource. The source is a factory for CancellationTokens. You pass this token on to everyone you want to be able to cancel its processing in a neat way. When you want to cancel all processes that has a CancellationToken from the same CancellationTokenSource, just tell the CancellationTokenSource to send a cancel to all CancellationTokens it producted, thus cancelling all processes that have tokens from this source.

And the nice thing is, a CancellationTokenSource has a CancelAfter(some timeout).

Its good practice, to let your process starter give you the cancellationToken, so your process starter can decide which processes it wants to cancel in one call.

public async Task<MyResult> MyProcessAsync(CancellationToken cancellationToken, ...)
{
    // do something lengthy processing, without await, regularly check if Cancellation requested
    while (stillProcessing)
    {
        cancellationToken.ThrowIfCancellationRequested();
        ... // process
    }

    // do some processing with async-await:
    await myDbContext.SaveChangesAsync(cancellationToken);
}

Usage:

private async Task LengthyProcessing(...)
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    tokenSource.CancelAfter(TimeSpan.FromSeconds(5));

    CancellationToken myCancellationToken = tokenSource.Token
    try
    {
       // Start one task, don't await yet:
       var myTask = await MyProcessAsync(myCancellationToken, ...)
       // during processing there will be regular check if cancellation requested
       // meanwhile, whenever myTask has to await, I can do some processing
       // I'll have to check for cancellation regularly also:

       while(...)
       {
           myCancellationToken.ThrowIfCancellationRequested();
           DoSomeProcessing();
           ...
       }

       MyResult result = await myTask;
       // if here, not cancelled. can use Result:
       ProcessResult(result);
    }
    catch (OperationCanceledException exc)
    {
        ProcessOperationCanceled();
    }
}

Note that only one CancelltionTokenSource is used. Whenever this source thinks that something should be cancelled, all threads that have tokens from this source get notified about the cancellationrequest.

Instead of using exception handling via CancellationToken.ThrowIfCancellationRequested() consider using bool CancellationToken.IsCancellationRequested.

MSDN how to cancel a task and its children


问:
UIMA Ruta Check Feature of sub Annotation
Is it possible to make a rule to match the value of a FEATURE in an annotation that is a child of another Annotation?

Example:

Annotation Person
   Annotation Doctor
             Feature TYPE: xyz

something like Person.Doctor{FEATURE("TYPE","xyz")}

Also is it possible to create a rule that matches a FEATURE in an annotation that is PARTOF another annotation?

|-----------A1------------|

|-----A2-----|    |---A3----|

Make a rule where

A3{FEATURE("X","1")} but also A3{PARTOF(A1)}

Thank you!

答:
Assuming that there is a type Doctor and its parent type called Person which defined a feature kind of type uima.cas.String, you can simply write:

```<code>Doctor.kind=="xyz";

Doctor{Doctor.kind=="xyz"};

d:Doctor{d.kind=="xyz"};

Doctor<-{Person.kind=="xyz";};
</code>```

Some short explanation of the label expression d: and the inlined rule as condition (<-{}). The label expression introduces a local annotation variable within the scope of the rule. In the above example d:Doctor matches on a annotation of the type Doctor and assigns it to a new variable called d. This variables can then be used in other parts of the rule in order to refer to this specific annotation. In the second rule, no label expression is used and the annotation is refered to by using the type (Doctor.kind). Here, the annotation is resolved anew in the context of the match of the rule, which could lead to a different one in case there are several annotations of the type Doctorwith the same offsets.
The inlined rule as condition works as a complex condition. The rule element Doctor matches only if the rule Person.kind=="xyz"; is able to match within the context/offsets/span of the matched Doctor annotation.

Concerning the second part of the question:
You cannot directly access the annotation which is used in a PARTOF condition because none is used actually. You need to match on the annotation in order to access its features. It depends on which annotation coveres which one, and which annotation should be checked for the feature value. Here are some examples:

```<code>a:A3{PARTOF(A1),a.x==1};

A1.x=="1"{CONTAINS(A3)};

A1<-{a:A3{a.x=="1"};};
</code>```

DISCLAIMER: I am a developer of UIMA Ruta

Body:
Assuming that there is a type Doctor and its parent type called Person which defined a feature kind of type uima.cas.String, you can simply write:

Doctor.kind=="xyz";

Doctor{Doctor.kind=="xyz"};

d:Doctor{d.kind=="xyz"};

Doctor<-{Person.kind=="xyz";};

Some short explanation of the label expression d: and the inlined rule as condition (<-{}). The label expression introduces a local annotation variable within the scope of the rule. In the above example d:Doctor matches on a annotation of the type Doctor and assigns it to a new variable called d. This variables can then be used in other parts of the rule in order to refer to this specific annotation. In the second rule, no label expression is used and the annotation is refered to by using the type (Doctor.kind). Here, the annotation is resolved anew in the context of the match of the rule, which could lead to a different one in case there are several annotations of the type Doctorwith the same offsets.
The inlined rule as condition works as a complex condition. The rule element Doctor matches only if the rule Person.kind=="xyz"; is able to match within the context/offsets/span of the matched Doctor annotation.

Concerning the second part of the question:
You cannot directly access the annotation which is used in a PARTOF condition because none is used actually. You need to match on the annotation in order to access its features. It depends on which annotation coveres which one, and which annotation should be checked for the feature value. Here are some examples:

a:A3{PARTOF(A1),a.x==1};

A1.x=="1"{CONTAINS(A3)};

A1<-{a:A3{a.x=="1"};};

DISCLAIMER: I am a developer of UIMA Ruta


问:
Cannot implement delete in Rails controller
I'm following this tutorial to built a simple blogger side.

However, I am unable to implement the delete function as shown by the tutorial.

The steps given are as follows:

Let’s define the destroy method in our ArticlesController so it:

Uses params[:id] to find the article in the database

Calls .destroy on that object

Redirects to the articles index page

Do that now on your own and test it.

This is my code:

```<code>class ArticlesController < ApplicationController
    include ArticlesHelper

    def index
        @articles = Article.all
    end

    def show
        @article = Article.find(params[:id])
    end

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)
        @article.save
        flash.notice = "Article '#{@article.title}' Created!"
        redirect_to article_path(@article)
    end

    def destroy
        @article = Article.find(params[:id])
        @article.destroy
        redirect_to articles_path
    end
end
</code>```

show.html.erb

```<code><h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<%= link_to "<< Back to Articles List", articles_path %>
<%= link_to "delete", article_path(@article), method: :delete %>
</code>```

article_helper.rb

```<code>module ArticlesHelper

  def article_params
    params.require(:article).permit(:title, :body)
  end

end
</code>```

I have browsed through other solutions online but I don't see any code which I might have missed out.

In my case, clicking on the delete link only results in the page refreshing.

答: private methods in controllers are not accessible outside the controller, even to routes. So you'll never be able to route to destroy or article_params in your current code. If you move your destroy method above the private keyword, should fix things.

Body:
I'm following this tutorial to built a simple blogger side.

However, I am unable to implement the delete function as shown by the tutorial.

The steps given are as follows:

Let’s define the destroy method in our ArticlesController so it:

Uses params[:id] to find the article in the database

Calls .destroy on that object

Redirects to the articles index page

Do that now on your own and test it.

This is my code:

class ArticlesController < ApplicationController
    include ArticlesHelper

    def index
        @articles = Article.all
    end

    def show
        @article = Article.find(params[:id])
    end

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)
        @article.save
        flash.notice = "Article '#{@article.title}' Created!"
        redirect_to article_path(@article)
    end

    def destroy
        @article = Article.find(params[:id])
        @article.destroy
        redirect_to articles_path
    end
end

show.html.erb

<%= @article.title %>

<%= @article.body %>

<%= link_to "<< Back to Articles List", articles_path %>
<%= link_to "delete", article_path(@article), method: :delete %>

article_helper.rb

module ArticlesHelper

  def article_params
    params.require(:article).permit(:title, :body)
  end

end

I have browsed through other solutions online but I don't see any code which I might have missed out.

In my case, clicking on the delete link only results in the page refreshing.


问:
How to achieve this font appearance?
How can I acheive a font like this?

It's the name below icons on the iOS platform.  Is it Helvetica, and how can I achieve the soft shadow that it has in code?  Thanks in advance!

答:
you can do it using Quartz 2D.

A shadow is an image painted
  underneath, and offset from, a
  graphics object such that the shadow
  mimics the effect of a light source
  cast on the graphics object, as shown
  in Figure 7-1. Text can also be
  shadowed. Shadows can make an image
  appear three dimensional or as if it’s
  floating.

look here:

http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_shadows/dq_shadows.html%23//apple_ref/doc/uid/TP30001066-CH208-TPXREF101

good luck

Title: How to achieve this font appearance?


问:
Git error: could not commit config file
I'm trying to add a new remote repository (GitHub) to an existing project, and I'm getting an error that I've never seen before, and don't understand:

```<code>$ git remote add github git@github.com:me/myrepo.git
error: could not commit config file .git/config
</code>```

What? Why would I commit the git config file? And how do I make this stop happening?

I'm on a Mac, with a relatively fresh install of most of my tools. I think this is the first time I've tried to add a remote to a repo on this machine.

答:
This could be a permissions issue, especially for automated jobs running on Windows that can have fewer permissions than an interactive login of the same user. From this answer on ServerFault:

Each logon session to a Windows (NT-based versions, that is) machine
  has a "security token"-- a data structure that describes, amongst
  other things, the groups that the user represented by the token is a
  member of.

The "Interactive" identity isn't a group that you can manually place
  members into, but rather is added by the operating system,
  automatically, when a security token is constructed for a user who has
  logged-on via the Windows Graphical User Interface. This is similar to
  the "Network" identity, which is added automatically to tokens created
  for users who are accessing the machine via the network.

These automatically-generated group memberships allow you to construct
  permissions that might allow or deny access to resources based on how
  the user is accessing the machine. This supplements the permission
  system's default behavior of arbitrating access based on who is
  accessing the resource.

Title: Git error: could not commit config file

Body:
I'm trying to add a new remote repository (GitHub) to an existing project, and I'm getting an error that I've never seen before, and don't understand:

$ git remote add github git@github.com:me/myrepo.git
error: could not commit config file .git/config

What? Why would I commit the git config file? And how do I make this stop happening?

I'm on a Mac, with a relatively fresh install of most of my tools. I think this is the first time I've tried to add a remote to a repo on this machine.


问:
Merge two table based on row name
I need to merge two table into one based on Row name, each table has 172 rows and 172 columns example of my data look

```<code>#table 1
A B C
1 2 3
2 3 4
5 6 7

#table 2
A B C
1 3 8
2 4 6
5 4 2
</code>```

I want my output like this

```<code>A B C
1 2 3
1 3 8
2 3 4
2 4 6
5 6 7
5 4 2
</code>```

答:
rbind is the function you are looking for. </p>

```<code>rbind(df1,df2)
</code>```

Title: Merge two table based on row name

Body:
I need to merge two table into one based on Row name, each table has 172 rows and 172 columns example of my data look

#table 1
A B C
1 2 3
2 3 4
5 6 7

#table 2
A B C
1 3 8
2 4 6
5 4 2

I want my output like this

A B C
1 2 3
1 3 8
2 3 4
2 4 6
5 6 7
5 4 2

Body:
rbind is the function you are looking for.

rbind(df1,df2)


问:
Insert (INSERT INTO) a table into another table containing a sequence (SERIAL)
I have a main table created as:

```<code>    CREATE TABLE main_data
    (
      id SERIAL NOT NULL,
      name character varying(249),
      telephone character varying(248)
    )
</code>```

While I get a new table backup_date containing only name and telephone which I restore and add to my database.

Now I want to add the backup_date to the main_data so that when the backup_date table is added to the main_table it automatically continues the sequence of id. How can I do that?

NOTE After a lot of searching I can only got this solution;

INSERT INTO users (name, age, id) VALUES ('Mozart', 20, DEFAULT);

as I have huge amount of data in the backup_date I cannot use it.

答:
Hi Hassan -

If your ID column is auto increment then just your code will be -

```<code>insert into main_data (name,telephone) select name,telephone from backup_date where [your condition]
</code>```

And if your ID column is not auto increment then first set it auto increment and then execute above query. Thanks :)

Body:
I have a main table created as:

    CREATE TABLE main_data
    (
      id SERIAL NOT NULL,
      name character varying(249),
      telephone character varying(248)
    )

While I get a new table backup_date containing only name and telephone which I restore and add to my database.

Now I want to add the backup_date to the main_data so that when the backup_date table is added to the main_table it automatically continues the sequence of id. How can I do that?

NOTE After a lot of searching I can only got this solution;

INSERT INTO users (name, age, id) VALUES ('Mozart', 20, DEFAULT);

as I have huge amount of data in the backup_date I cannot use it.

Body:
Hi Hassan -

If your ID column is auto increment then just your code will be -

insert into main_data (name,telephone) select name,telephone from backup_date where [your condition]

And if your ID column is not auto increment then first set it auto increment and then execute above query. Thanks :)


问:
Pseudonymisation within ASP.NET MVC/SQL Azure web application?
I am exploring how I can implement Pseudonymisation within my ASP.NET MVC/ SQL Azure Web Application.

I am struggling how to do this within Azure.

Current thoughts include:

1) Another secure SQL Azure DB with the Personal Data and key

2) Another secure data storage mechanism within Azure for this type of data ie "Azure Key Vault".

Advice appreciated.

答:
It seems that you’d like to implement Pseudonymisation for your data records to replace the identifying fields of data records with pseudonyms. As you mentioned ( Another secure SQL Azure DB with the Personal Data and key ), Azure SQL Database can be used to separately store correspondence of "identifying fields-pseudonyms", and Azure can help keep customer data safe.

Besides, you could refer to this article that shows the information about securing Azure SQL Database.


问:
'didSelectRowAt' is not being called
i have a question about the UITableView delegate function didSelectRowAt. Everything is working fine but unfortunately the didSelectRowAt is not called. I read in some other stackoverflow question about the problem and tried some solutions out but none of them works for me. I made a subclass of the tableview which is the delegate himself:

```<code>class MyTableView : UITableView, UITableViewDelegate{

    override func awakeFromNib() {

        super.awakeFromNib()

        separatorStyle = .none

        backgroundView = nil
        backgroundColor = UIColor.clear

        isScrollEnabled = false

        delegate = self
        isEditing = false
        allowsSelection = true

    }

//    func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
//
//    this is working
//
//    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("not called")

    }

}
</code>```

So all subclasses of MyTableView will implement the datasource stuff and this also working fine (in case somehow will mentioned this).

The strange thing is that didHighlightRowAt is called, so the delegate somehow works. Only the didSelectRowAt which I want is not being called.

By the way there aren't any UITapGestureRecognizer.

Can somehow give me any advice here. Are there properties which are wrong?

答:
Please check TableView's cell allowsSelection.

```<code>tableView.allowsSelection = true
</code>```

Edit:

Check:

tableView.allowsSelection

cell.selectionStyle

User Interaction Enabled

Title: 'didSelectRowAt' is not being called

Body:
i have a question about the UITableView delegate function didSelectRowAt. Everything is working fine but unfortunately the didSelectRowAt is not called. I read in some other stackoverflow question about the problem and tried some solutions out but none of them works for me. I made a subclass of the tableview which is the delegate himself:

class MyTableView : UITableView, UITableViewDelegate{

    override func awakeFromNib() {

        super.awakeFromNib()

        separatorStyle = .none

        backgroundView = nil
        backgroundColor = UIColor.clear

        isScrollEnabled = false

        delegate = self
        isEditing = false
        allowsSelection = true

    }

//    func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
//
//    this is working
//
//    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("not called")

    }

}

So all subclasses of MyTableView will implement the datasource stuff and this also working fine (in case somehow will mentioned this).

The strange thing is that didHighlightRowAt is called, so the delegate somehow works. Only the didSelectRowAt which I want is not being called.

By the way there aren't any UITapGestureRecognizer.

Can somehow give me any advice here. Are there properties which are wrong?

Body:
Please check TableView's cell allowsSelection.

tableView.allowsSelection = true

Edit:

Check:

tableView.allowsSelection

cell.selectionStyle

User Interaction Enabled


问:
Cannot play pcm > 60kb with the AndroidSimpleBufferQueue
I've initialized an AndroidSimpleBufferQueue such as values:

```<code>SLDataLocator_AndroidSimpleBufferQueue bufferLocator = {
  SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};
SLDataFormat_PCM pcmFormat = {
  SL_DATAFORMAT_PCM,           1,
  SL_SAMPLINGRATE_44_1,        SL_PCMSAMPLEFORMAT_FIXED_16,
  SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_CENTER,
  SL_BYTEORDER_LITTLEENDIAN};

SLDataSource            audioSource      = {&bufferLocator, &pcmFormat};
SLDataLocator_OutputMix locatorOutputMix = {SL_DATALOCATOR_OUTPUTMIX,
                                            outputMixObj.getObject()};
SLDataSink audioSink = {&locatorOutputMix, nullptr};
[...]
</code>```

Then when I need to play a sound I enqueue such as:

```<code>bufferQueue->Enqueue(bufferQueue, (uint8_t*)buffer.data(),
          buffer.size())
</code>```

It works well for buffer smaller than 60k however when the buffer is bigger no sound are played or sometime just an artifact.

答:
From the Specifications:

The buffers that are queued are used in place and are not required to
  be copied by the  device, although this may  be
  implementation-dependent. The application developer  should be aware
  that modifying the content  of a buffer after it has been queued is
  undefined and can cause audio corruption

So the memory must remains valid until the sound fully played.

Read the documentation and be aware of unintended struct copy :)

Body:
I've initialized an AndroidSimpleBufferQueue such as values:

SLDataLocator_AndroidSimpleBufferQueue bufferLocator = {
  SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};
SLDataFormat_PCM pcmFormat = {
  SL_DATAFORMAT_PCM,           1,
  SL_SAMPLINGRATE_44_1,        SL_PCMSAMPLEFORMAT_FIXED_16,
  SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_CENTER,
  SL_BYTEORDER_LITTLEENDIAN};

SLDataSource            audioSource      = {&bufferLocator, &pcmFormat};
SLDataLocator_OutputMix locatorOutputMix = {SL_DATALOCATOR_OUTPUTMIX,
                                            outputMixObj.getObject()};
SLDataSink audioSink = {&locatorOutputMix, nullptr};
[...]

Then when I need to play a sound I enqueue such as:

bufferQueue->Enqueue(bufferQueue, (uint8_t*)buffer.data(),
          buffer.size())

It works well for buffer smaller than 60k however when the buffer is bigger no sound are played or sometime just an artifact.


问:
how to dynamically insert column value into table2 select * from another table1 which is having one column less than table2
table1 :

```<code>t1_column1  t1_column2  t1_column3
 1           2           3
 2           3           4
</code>```

```<code>table2 is :

t2_column1  t2_column2  t2_column3   t2_column4
 1           2           3             0
 2           3           4             0
</code>```

Here I am passing the value as function argument, but when I am
  trying to create this function getting this error : Error(11,7):
  PL/SQL: SQL Statement ignored   and Error(11,108): PL/SQL: ORA-00917:
  missing comma

```<code>CREATE OR REPLACE FUNCTION NEW_PURCHASE(GODOWN_CODE IN VARCHAR2,MON IN
VARCHAR2)
   RETURN VARCHAR2 IS
   var_mon VARCHAR2(100);
   PRAGMA AUTONOMOUS_TRANSACTION;

BEGIN
var_mon:=MON;

  INSERT INTO table2
( t2_column1, t2_column2, t2_column3, var_mon)
SELECT  t1_column1, t1_column2, t1_column3
FROM table1   WHERE  t1_column1=GODOWN_CODE;
  DELETE FROM table1 WHERE  t1_column1=GODOWN_CODE;

    COMMIT;
  RETURN 'done';
 END NEW_PURCHASE;
</code>```

答:
Try this:

```<code>CREATE OR REPLACE FUNCTION NEW_PURCHASE (GODOWN_CODE   IN VARCHAR2,
                                         MON           IN VARCHAR2)
   RETURN VARCHAR2
IS
   --var_mon   VARCHAR2 (100);
   PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
   --var_mon := 'MON';

   INSERT INTO table2 (t2_column1,
                       t2_column2,
                       t2_column3,
                       t2_column4)
      SELECT t1_column1, t1_column2, t1_column3, mon
      FROM table1
       WHERE t1_column1 = GODOWN_CODE;

   DELETE FROM table1
         WHERE t1_column1 = GODOWN_CODE;

   COMMIT;
   RETURN 'done';
END NEW_PURCHASE;
</code>```

Note that if you do DML operation in a function, you cannot call it from a select statement, You would need a PLSQL block to run it.

For ex:

You can call it as below:

```<code>declare
   l_message varchar2(30);
begin
   l_message := test_func('123');
end;
</code>```

... but not like this:

```<code>select test_func(empno) from emp;
</code>```

Body:
table1 :

t1_column1  t1_column2  t1_column3
 1           2           3
 2           3           4

table2 is :

t2_column1  t2_column2  t2_column3   t2_column4
 1           2           3             0
 2           3           4             0

Here I am passing the value as function argument, but when I am
  trying to create this function getting this error : Error(11,7):
  PL/SQL: SQL Statement ignored   and Error(11,108): PL/SQL: ORA-00917:
  missing comma

CREATE OR REPLACE FUNCTION NEW_PURCHASE(GODOWN_CODE IN VARCHAR2,MON IN
VARCHAR2)
   RETURN VARCHAR2 IS
   var_mon VARCHAR2(100);
   PRAGMA AUTONOMOUS_TRANSACTION;

BEGIN
var_mon:=MON;

  INSERT INTO table2
( t2_column1, t2_column2, t2_column3, var_mon)
SELECT  t1_column1, t1_column2, t1_column3
FROM table1   WHERE  t1_column1=GODOWN_CODE;
  DELETE FROM table1 WHERE  t1_column1=GODOWN_CODE;

    COMMIT;
  RETURN 'done';
 END NEW_PURCHASE;

Body:
Try this:

CREATE OR REPLACE FUNCTION NEW_PURCHASE (GODOWN_CODE   IN VARCHAR2,
                                         MON           IN VARCHAR2)
   RETURN VARCHAR2
IS
   --var_mon   VARCHAR2 (100);
   PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
   --var_mon := 'MON';

   INSERT INTO table2 (t2_column1,
                       t2_column2,
                       t2_column3,
                       t2_column4)
      SELECT t1_column1, t1_column2, t1_column3, mon
      FROM table1
       WHERE t1_column1 = GODOWN_CODE;

   DELETE FROM table1
         WHERE t1_column1 = GODOWN_CODE;

   COMMIT;
   RETURN 'done';
END NEW_PURCHASE;

Note that if you do DML operation in a function, you cannot call it from a select statement, You would need a PLSQL block to run it.

For ex:

You can call it as below:

declare
   l_message varchar2(30);
begin
   l_message := test_func('123');
end;

... but not like this:

select test_func(empno) from emp;


问:
how to communicate peer to peer in hyperledger fabric local network
I've created hyperledger fabric local network in system(Ubuntu) which contains 4 peers using docker composer, config.yml file.
I'm able to create users in a single peer by using membersrvc. But, how to do transactions between two users.</p>

答:
I don't understant very well your question. What do you mean? Do you want to communicate with the peers?

The peers communicate among them through the channels. When you define a channel, you decide who are going to be part of it. Then, the transactions that are executed against that channel are viewd by all the members of the channel.

Users call the Peers and do the transactions

You don't do the transactions among Peers or between users. You call to a smartcontract (chaincode in Hyperledger) that you have installed in a channel


答:
The problem seems to be that the password is being sent with a spawn command rather than a send command. Additionally, ssh can be called with a specific command to run during the session, for example:

```<code>#!/usr/bin/expect
set timeout 20
set port [lindex $argv 0]
set ip [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]
spawn ssh $user@$ip -p $port "cd /etc/abcd/; rm -f efg/*; . somescriptinefg.sh"
expect "password:*"
send "$password\r"
expect eof
</code>```

It might be worth configuring ssh keys for passwordless access instead. This would eliminate the need for an expect script and reduce the whole thing to a single line. If you really need to have an interactive ssh session, then a tool such as sshpass could be a less impractical alternative.

Title: How to execute a command on server using Expect

Body:
I want to remotely delete a file/execute another script on my server. Manually this could be done by ssh-login -> cd /path/ -> rm somefiles -> . script.sh

I want to automatic this process. So that when I execute expect expectscript.sh port serverip user userpasswd, the script would do the whole process for me.

So I write the following script. Things go smoothly till the ssh-login process finished. I don't know what is wrong with the last 3 lines of the code. Could someone help?

#!/usr/bin/expect
set timeout 20
set port [lindex $argv 0]
set ip [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]
spawn ssh "$user\@$ip" "-p" "$port"
expect "password:"
send "$password\r"
spawn "cd /etc/abcd/"
spawn "rm -f efg/*"
spawn ". somescriptinefg.sh"

Body:
The problem seems to be that the password is being sent with a spawn command rather than a send command. Additionally, ssh can be called with a specific command to run during the session, for example:

#!/usr/bin/expect
set timeout 20
set port [lindex $argv 0]
set ip [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]
spawn ssh $user@$ip -p $port "cd /etc/abcd/; rm -f efg/*; . somescriptinefg.sh"
expect "password:*"
send "$password\r"
expect eof

It might be worth configuring ssh keys for passwordless access instead. This would eliminate the need for an expect script and reduce the whole thing to a single line. If you really need to have an interactive ssh session, then a tool such as sshpass could be a less impractical alternative.


问:
Check if ALL elements of list A within list B
I have done my research, however all these techniques return true, i need them to return false.

```<code>print set([2, 2]).issubset([2, 3, 3]) #returns True
print set([2, 3, 3]).issuperset(set([2, 2])) #returns True
print all(x in {2, 3, 3} for x in [2, 2]) #returns True
print set([2, 2]) <= set([2, 3, 3]) #returns True
</code>```

The lists I'm comparing have duplicate numbers

答:
How about this:

```<code>a = [2, 2]
b = [2, 3, 3]

from collections import Counter as cC

fa = cC(a)
print(fa)  # Counter({2: 2})
fb = cC(b)
print(fb)  # Counter({3: 2, 2: 1})

test = all(fa[entry] <= fb.get(entry, -1e+30) for entry in fa)

print(test)  # False
</code>```

Or according to what @ChrisRand said in the comments:

```<code>test = fa - fb == {}
print(test)  # False
</code>```

Body:
I have done my research, however all these techniques return true, i need them to return false.

print set([2, 2]).issubset([2, 3, 3]) #returns True
print set([2, 3, 3]).issuperset(set([2, 2])) #returns True
print all(x in {2, 3, 3} for x in [2, 2]) #returns True
print set([2, 2]) <= set([2, 3, 3]) #returns True

The lists I'm comparing have duplicate numbers

Body:
How about this:

a = [2, 2]
b = [2, 3, 3]

from collections import Counter as cC

fa = cC(a)
print(fa)  # Counter({2: 2})
fb = cC(b)
print(fb)  # Counter({3: 2, 2: 1})

test = all(fa[entry] <= fb.get(entry, -1e+30) for entry in fa)

print(test)  # False

Or according to what @ChrisRand said in the comments:

test = fa - fb == {}
print(test)  # False


问:
Get id items of the array and push them to a new one
I've got an

```<code>$array = array(1,22,54,75,90,364)
</code>```

How is it posaible to create a new array of it's id items?

```<code>$newarray = $array[i];
</code>```

Thanks

答:
If I understand you correctly, you can simply use array_keys()

```<code>$newarray = array_keys($array);
</code>```

Body:
I've got an

$array = array(1,22,54,75,90,364)

How is it posaible to create a new array of it's id items?

$newarray = $array[i];

Thanks

Body:
If I understand you correctly, you can simply use array_keys()

$newarray = array_keys($array);


问:
Item position in list
I have this dictionary:

```<code>db= {'www.baurom.ro':
                     {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                     },
    'slbz2':
            {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    }
</code>```

And a list:

```<code>lista=['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']
</code>```

What am i doing now is this:

```<code>for x in lista:
     if x in db:
        db[x][0][lista.index(x)]+=1
</code>```

In other words i want to count how many times each site appears in the list and on which position. This works but in the given example it will return something like:

```<code>{0: [7, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

while i would want it to be:

```<code>{0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
</code>```

How can i achieve this? I can use a variable, initiate it with var=0 and then +=1 and use it as an artificial index but is there a more "pythonic" way of doing it?

答:
If I understand your problem correctly, you could just iterate over lista and create db as needed :

```<code>urls = ['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']
n = len(urls)
db = {}

for i, url in enumerate(urls):
    if not db.get(url):
        db[url] = {0: [0] * n} # NOTE: Use numpy for large arrays
    db[url][0][i] = 1

print(db)
# {'www.romanian-companies.eu': {0: [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]}, 'www.risco.ro': {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]}, 'www.listafirme.ro': {0: [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]}, 'www.baurom.ro': {0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]}}
</code>```

It requires only one pass over lista and should be really fast.

If you have a list of interesting urls, you could use this variant:

```<code>from collections import defaultdict

urls = ['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']

interesting_urls = set(['www.baurom.ro', 'slbz2'])

n = len(urls)

def url_array():
    return {0: [0] * n, 1: [0] * n}

db = defaultdict(url_array)

for i, url in enumerate(urls):
    if url in interesting_urls:
        db[url][0][i] = 1

print(db)
# defaultdict(<function url_array at 0x7fe8a95b87d0>, {'www.baurom.ro': {0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}})
</code>```

Title: Item position in list

Body:
I have this dictionary:

db= {'www.baurom.ro':
                     {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                     },
    'slbz2':
            {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    }

And a list:

lista=['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']

What am i doing now is this:

for x in lista:
     if x in db:
        db[x][0][lista.index(x)]+=1

In other words i want to count how many times each site appears in the list and on which position. This works but in the given example it will return something like:

{0: [7, 0, 0, 0, 0, 0, 0, 0, 0, 0]

while i would want it to be:

{0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]

How can i achieve this? I can use a variable, initiate it with var=0 and then +=1 and use it as an artificial index but is there a more "pythonic" way of doing it?

Body:
If I understand your problem correctly, you could just iterate over lista and create db as needed :

urls = ['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']
n = len(urls)
db = {}

for i, url in enumerate(urls):
    if not db.get(url):
        db[url] = {0: [0] * n} # NOTE: Use numpy for large arrays
    db[url][0][i] = 1

print(db)
# {'www.romanian-companies.eu': {0: [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]}, 'www.risco.ro': {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]}, 'www.listafirme.ro': {0: [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]}, 'www.baurom.ro': {0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]}}

It requires only one pass over lista and should be really fast.

If you have a list of interesting urls, you could use this variant:

from collections import defaultdict

urls = ['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']

interesting_urls = set(['www.baurom.ro', 'slbz2'])

n = len(urls)

def url_array():
    return {0: [0] * n, 1: [0] * n}

db = defaultdict(url_array)

for i, url in enumerate(urls):
    if url in interesting_urls:
        db[url][0][i] = 1

print(db)
# defaultdict(<function url_array at 0x7fe8a95b87d0>, {'www.baurom.ro': {0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0], 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}})