问:
How to pass a location parameter in when calculating distance?
I would like to execute the following query from my Go application

```<code>SELECT hour, count
FROM location_counts
WHERE distance(point, 'POINT(-80.205 26.14)') <= 100
</code>```

I will be passing in the POINT(-80.205 26.14) and 100 values and I'm not quite sure how to include the POINT... parameter in a secure way.  When I try to pass it in as a parameter like below:

```<code>rows, err := g.DB.Query(
    "select hour, count from location_counts where distance(point, '?') <= ?",
    "POINT(-80.205 26.14)",
    100,
)
</code>```

It throws the error:

SQLActionException[SQLParseException: Cannot cast 'POINT(-80.205
  26.14)' to type double]

If I drop the value directly into the string it works but I would open myself up for SQL Injection vulnerabilities.

How can I securely include the POINT... value in my query?

答:
Removing the surrounding quotes of the placeholder question mark should fix it, like:

rows, err := g.DB.Query(
    "select hour, count from location_counts where distance(point, ?) <= ?",
    "POINT(-80.205 26.14)",
    100,
)

Placeholders should never be quoted as they will be replaced directly by the typed parameter.

Body:
I would like to execute the following query from my Go application

SELECT hour, count
FROM location_counts
WHERE distance(point, 'POINT(-80.205 26.14)') <= 100

I will be passing in the POINT(-80.205 26.14) and 100 values and I'm not quite sure how to include the POINT... parameter in a secure way.  When I try to pass it in as a parameter like below:

rows, err := g.DB.Query(
    "select hour, count from location_counts where distance(point, '?') <= ?",
    "POINT(-80.205 26.14)",
    100,
)

It throws the error:

SQLActionException[SQLParseException: Cannot cast 'POINT(-80.205
  26.14)' to type double]

If I drop the value directly into the string it works but I would open myself up for SQL Injection vulnerabilities.

How can I securely include the POINT... value in my query?


来源: stackexchange

问:
Wait for mongo writes before returning from a find
I want a store js object that manages a mongodb collection and behaves like that:

```<code>store.insert(thing); // called from a pubsub system that don't wait the insert to finish

store.get(); // returns a promise that resolves to the things in the collection
// even if called immediately after insert it must contain the last thing inserted
</code>```

I implemented it manually like that:

```<code>let inserts = 0;
let afterInserts = [];

const checkInsertsFinished = () => {
  if (inserts === 0) {
    afterInserts.forEach(resolve => resolve());
    afterInserts = [];
  }
};

const decrementInserts = () => {
  inserts -= 1;
  checkInsertsFinished();
};

const insertsFinished = () =>
  new Promise((resolve) => {
    afterInserts.push(resolve);
    checkInsertsFinished();
  });

const insert = (thing) => {
  inserts += 1;
  db.collection('mycollection').insertOne(thing).then(decrementInserts);
};

const get = async () => {
  await insertsFinished(); // if there are inserts happening, wait for them to finish
  return db.collection('mycollection').find({}).toArray();
};

return { insert, get };
</code>```

I suppose that there are more standard ways to accomplish this but I miss the vocabulary to find libs or built-in features... How would you do that?

Thanks for your advices.

答:
JavaScript is single threaded, none of code you write can be run at the same time on multiple threads so you should be able to do it this way:</p>

```<code>let inserting = Promise.resolve(),
startGetting={};

const insert = (thing) => {
  startGetting={};//de-reference startGetting
  inserting = db.collection('mycollection').insertOne(thing)
  return inserting;
};

const get = () => {
  const rec = () =>
    inserting.then(
      _ =>
        new Promise(
          (resolve,reject)=>{
            //the next op is truely async (although I wonder why no promise),
            //  someone can insert while this is completing
            const start=startGetting;
            db.collection('mycollection').find({}).toArray(
              (err,results)=>
                err
                  ? reject(err)
                  //inserting could have been set to tby the time
                  //  this completed (in theory) so use startGetting reference equality
                  : startGetting === start
                    ? resolve(results)//while getting nobody inserted
                    : resolve(rec())
          )
        })
    );
  return rec();
};

return { insert, get };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want a store js object that manages a mongodb collection and behaves like that:

store.insert(thing); // called from a pubsub system that don't wait the insert to finish

store.get(); // returns a promise that resolves to the things in the collection
// even if called immediately after insert it must contain the last thing inserted

I implemented it manually like that:

let inserts = 0;
let afterInserts = [];

const checkInsertsFinished = () => {
  if (inserts === 0) {
    afterInserts.forEach(resolve => resolve());
    afterInserts = [];
  }
};

const decrementInserts = () => {
  inserts -= 1;
  checkInsertsFinished();
};

const insertsFinished = () =>
  new Promise((resolve) => {
    afterInserts.push(resolve);
    checkInsertsFinished();
  });

const insert = (thing) => {
  inserts += 1;
  db.collection('mycollection').insertOne(thing).then(decrementInserts);
};

const get = async () => {
  await insertsFinished(); // if there are inserts happening, wait for them to finish
  return db.collection('mycollection').find({}).toArray();
};

return { insert, get };

I suppose that there are more standard ways to accomplish this but I miss the vocabulary to find libs or built-in features... How would you do that?

Thanks for your advices.

Body:
JavaScript is single threaded, none of code you write can be run at the same time on multiple threads so you should be able to do it this way:

let inserting = Promise.resolve(),
startGetting={};

const insert = (thing) => {
  startGetting={};//de-reference startGetting
  inserting = db.collection('mycollection').insertOne(thing)
  return inserting;
};

const get = () => {
  const rec = () =>
    inserting.then(
      _ =>
        new Promise(
          (resolve,reject)=>{
            //the next op is truely async (although I wonder why no promise),
            //  someone can insert while this is completing
            const start=startGetting;
            db.collection('mycollection').find({}).toArray(
              (err,results)=>
                err
                  ? reject(err)
                  //inserting could have been set to tby the time
                  //  this completed (in theory) so use startGetting reference equality
                  : startGetting === start
                    ? resolve(results)//while getting nobody inserted
                    : resolve(rec())
          )
        })
    );
  return rec();
};

return { insert, get };


问:
jQuery Form Submit Function Ignored On Change
I'm trying to execute a function on form submit whenever another html element is changed. However, the function inside my form submit seems to be ignored.

```<code>$("element1").change(function(){
    alert("Works!");
    $("#form").submit(function() {
        console.log("Submitted!");
    });
});
</code>```

The "Works!" alert displays but for some reason it will not print "Submitted!" to the console and I'm unsure why. Is it possible to execute a function within a form submit if it's being triggered by another element ".change" event? Thank you in advance.

EDIT: I forgot to mention, I need my code to invoke a form submission when this field is changed. Ultimately, I'm having users upload a csv and after it's selected from the file explorer it submits the form. I would like to keep the user on the same page after the file is uploaded as well.

答:
All you have to do is trigger the submit function like this

```<code>$("#form").submit();//Triggers the submit function.
</code>```

However, the code you have written is not the write way to write it.You don't want submit event to be binded to the form every time the element is changed.
So it can be rephrased as

```<code>/*In this case the event binding happens only once*/
$("#form").submit(function() {
    console.log("Submitted!");
});
/*Now simply trigger it when the element is changed*/
$("element1").change(function() {
    alert("Works!");
    $("#form").submit();
});
</code>```

For you clear understanding have a look at this fiddle

Body:
I'm trying to execute a function on form submit whenever another html element is changed. However, the function inside my form submit seems to be ignored.

$("element1").change(function(){
    alert("Works!");
    $("#form").submit(function() {
        console.log("Submitted!");
    });
});

The "Works!" alert displays but for some reason it will not print "Submitted!" to the console and I'm unsure why. Is it possible to execute a function within a form submit if it's being triggered by another element ".change" event? Thank you in advance.

EDIT: I forgot to mention, I need my code to invoke a form submission when this field is changed. Ultimately, I'm having users upload a csv and after it's selected from the file explorer it submits the form. I would like to keep the user on the same page after the file is uploaded as well.

Body:
All you have to do is trigger the submit function like this

$("#form").submit();//Triggers the submit function.

However, the code you have written is not the write way to write it.You don't want submit event to be binded to the form every time the element is changed.
So it can be rephrased as

/*In this case the event binding happens only once*/
$("#form").submit(function() {
    console.log("Submitted!");
});
/*Now simply trigger it when the element is changed*/
$("element1").change(function() {
    alert("Works!");
    $("#form").submit();
});

For you clear understanding have a look at this fiddle


问:
Syncing Model with bare RxSwift and BehaviourSubject
i'm new to the world of swift and rxSwfit, and i'm asking for suggestions or criticism with this current solution for example, for syncing blog posts, categories, authors or whatever we need.

Take this classic situation: an observable which gives to every subscriber the last updated data present in the model, and since that moment on, for every synchronization of the model, it emits the new whole pack of data, so the subscribers get and operate on the updated data.

I built an observable who's next value is the combination of his current value (the data present in ram) with the value grabbed from the rest.

Take for the example, the posts:

```<code>let articoli2       = BehaviorSubject<[Articolo]>(value: [Articolo]()) // ram data, initially empty
var articoli_rest   = PublishSubject<[Articolo]>()  // net data
var idx_articoli2   = [Int:Articolo]()   // used for filtering duplicates
</code>```

Then i create the subscription which updates "articoli2"

```<code>Observable.zip(articoli2, articoli_rest) { (ram_articoli, rest_articoli) -> [Articolo] in
            var new_articoli = ram_articoli

//Code that merges the data currently present (ram_articoli)
//with the data grabbed from the net (rest_articoli)
...
            return new_articoli
            }.subscribe(onNext: { (articoli) in
                self.articoli2.onNext(articoli)

            }).disposed(by: disposeBag)
</code>```

Finally, when i want to update the model, i use:

```<code>func sync_articoli()
{
        get_rest_array(Articolo.self,"https://rest_route").retry(4)
            .subscribe(onNext: { (articoli) in
                    self.articoli_rest.onNext(articoli)
}
</code>```

This function subscribes to the single observable returned by get_rest_array
an when the data from the net is ready, it emits an item on articoli_rest
which in turn updates my articoli2.
The whole thing works but i'm not sure it's really usable and I'm not confident in my solution. Any words? ( blame as much you want )

答: Observable.zip() is an incorrect operator to use for pagination. There is a scan operator designed for that cause.

Body:
i'm new to the world of swift and rxSwfit, and i'm asking for suggestions or criticism with this current solution for example, for syncing blog posts, categories, authors or whatever we need.

Take this classic situation: an observable which gives to every subscriber the last updated data present in the model, and since that moment on, for every synchronization of the model, it emits the new whole pack of data, so the subscribers get and operate on the updated data.

I built an observable who's next value is the combination of his current value (the data present in ram) with the value grabbed from the rest.

Take for the example, the posts:

let articoli2       = BehaviorSubject<[Articolo]>(value: [Articolo]()) // ram data, initially empty
var articoli_rest   = PublishSubject<[Articolo]>()  // net data
var idx_articoli2   = [Int:Articolo]()   // used for filtering duplicates

Then i create the subscription which updates "articoli2"

Observable.zip(articoli2, articoli_rest) { (ram_articoli, rest_articoli) -> [Articolo] in
            var new_articoli = ram_articoli

//Code that merges the data currently present (ram_articoli)
//with the data grabbed from the net (rest_articoli)
...
            return new_articoli
            }.subscribe(onNext: { (articoli) in
                self.articoli2.onNext(articoli)

            }).disposed(by: disposeBag)

Finally, when i want to update the model, i use:

func sync_articoli()
{
        get_rest_array(Articolo.self,"https://rest_route").retry(4)
            .subscribe(onNext: { (articoli) in
                    self.articoli_rest.onNext(articoli)
}

This function subscribes to the single observable returned by get_rest_array
an when the data from the net is ready, it emits an item on articoli_rest
which in turn updates my articoli2.
The whole thing works but i'm not sure it's really usable and I'm not confident in my solution. Any words? ( blame as much you want )


问:
Django Mixing Static Pages With Django Apps
I have a Django project that has one database-driven (i.e. normal) Django app. I have a .php webpage that I would like to include within the Django project that is a D3 visualization based on CSV files. Is it possible and kosher to include this page that includes php, JavaScript, and references to static CSV files in the Django project? If so, how would it be accomplished?

I have seen flatpages, but the Django documentation and various tutorials make it seem like that is only for simple html pages.

答:
Django is web framework for the python language; in order to 'serve' your project pages you'll need a web server to take in the requests, and a  application server to process your ... python code!
When you're developping locally and use the runserver commands, it simulates both server for you to test your project locally.

Same goes to your php, it'll need both those components to serve the page.

When you want to expose your pages to the world, you don't want to use "runserver". You could use the same web server to serve both Django pages and your Php pages, such as Nginx (example of multi config) or Apache (example with a multi config).

You will need to "isolate" or "match" URLs for either running your php application server or the python one.


问:
Regular expression for specific character start and end
I am writing regular expression for words which start with T and ends with A.

I write:-

```<code>^T\..*A$
</code>```

But now I want to exclude the word TEA. How to exclude the specific word using the regular expression.

答:
If you want to find 'TEA' and 'TEEA' from this sample, 'TEA IS NOT TEEA'. You can try to use this regular expression.</p>

```<code>Pattern p = Pattern.compile("((T|t)[A-Za-z]+(A|a))");
Matcher m = p.matcher("TEA or tea IS NOT TEEA or teea");
while(m.find()) {
    System.out.println(m.group(1));
}
</code>```

Body:
I am writing regular expression for words which start with T and ends with A.

I write:-

^T\..*A$

But now I want to exclude the word TEA. How to exclude the specific word using the regular expression.

Body:
If you want to find 'TEA' and 'TEEA' from this sample, 'TEA IS NOT TEEA'. You can try to use this regular expression.

Pattern p = Pattern.compile("((T|t)[A-Za-z]+(A|a))");
Matcher m = p.matcher("TEA or tea IS NOT TEEA or teea");
while(m.find()) {
    System.out.println(m.group(1));
}


问:
HTML POST Submit button not working
I got my page which is a simple password unlocker, but the post submit form button won't work...

```<code><div class="content">
            <form action="/action_page.php" method="post">
                <div class="user-profile">
                    <div class="author">
                        <img class="avatar" src="../../assets/img/default-avatar.png" alt="...">
                    </div>
                    <h4>User Unlock</h4>
                    <div class="form-group">
                        <input type="password" placeholder="Enter Password" class="form-control">
                    </div>
                    <button type="button" class="btn btn-neutral btn-round btn-fil btn-wd">Unlock</button>
                </div>
            </form>
        </div>
</code>```

When I click the button nothing happens..

It does not redirect to action_page.php nor sends any data.

答:
Check new version.

You added <button>. You need to add <input type="submit"> .
Like this:

```<code><div class="content">
            <form action="/action_page.php" method="post">
                <div class="user-profile">
                    <div class="author">
                        <img class="avatar" src="../../assets/img/default-avatar.png" alt="...">
                    </div>
                    <h4>User Unlock</h4>
                    <div class="form-group">
                        <input type="password" placeholder="Enter Password" class="form-control">
                    </div>
                    <input type="submit" class="btn btn-neutral btn-round btn-fil btn-wd" value="Unlock">
                </div>
            </form>
        </div>
</code>```

Let me know if you have any problem.

Title: HTML POST Submit button not working

Body:
I got my page which is a simple password unlocker, but the post submit form button won't work...

            <form action="/action_page.php" method="post">

User Unlock

                        <input type="password" placeholder="Enter Password" class="form-control">

                    <button type="button" class="btn btn-neutral btn-round btn-fil btn-wd">Unlock</button>

            </form>

When I click the button nothing happens..

It does not redirect to action_page.php nor sends any data.

Body:
Check new version.

You added <button>. You need to add <input type="submit"> .
Like this:

<div class="content">
            <form action="/action_page.php" method="post">
                <div class="user-profile">
                    <div class="author">
                        <img class="avatar" src="../../assets/img/default-avatar.png" alt="...">
                    </div>
                    <h4>User Unlock</h4>
                    <div class="form-group">
                        <input type="password" placeholder="Enter Password" class="form-control">
                    </div>
                    <input type="submit" class="btn btn-neutral btn-round btn-fil btn-wd" value="Unlock">
                </div>
            </form>
        </div>

Let me know if you have any problem.


问:
Changing the color of only one world in a text view
I am create an android app with android studio that retrieves text from mysqli database using volley library into a text view. I want to check if the text contains "@"  and if to does it it should be coloured red. That Is, I want only the "@" to be changed. Please guys how will I achieve that?</p>

答:
use an if statement like

```<code>if text.contains("@") {
text.setTextColor(Color.RED);
}
</code>```

read here How to set the text color of TextView in code? to learn more about changing text color

Body:
use an if statement like

if text.contains("@") {
text.setTextColor(Color.RED);
}

read here How to set the text color of TextView in code? to learn more about changing text color


问:
laravel eloquent where in query not working on both array
How to use $a variable in wherein properly? My code is as follows:

```<code>$color = json_decode($request -> color); //["2","3"] from jquery ajax
$a;

foreach($color as $k){
    $a[] = $k;
}

$b =[2,3];
$query = $query->whereIn('color', $a);
</code>```

When I put $a array in whereIn, only one record is fetched. But if i add $b array then all records are fetched. I don't know what is the issue of both arrays.

答:
You can use array_map to convert every element in the array to integer:

```<code>$query->whereIn('color', array_map('intval', json_decode($request->color)));
</code>```

Body:
How to use $a variable in wherein properly? My code is as follows:

$color = json_decode($request -> color); //["2","3"] from jquery ajax
$a;

foreach($color as $k){
    $a[] = $k;
}

$b =[2,3];
$query = $query->whereIn('color', $a);

When I put $a array in whereIn, only one record is fetched. But if i add $b array then all records are fetched. I don't know what is the issue of both arrays.

Body:
You can use array_map to convert every element in the array to integer:

$query->whereIn('color', array_map('intval', json_decode($request->color)));


问:
chai reuse series of expects
How do I reuse a series of expects?
For example:

```<code>expect(savedUser).to.have.all.keys(['fbId', 'fbName', 'gender', 'birthdate', 'aboutMe']);
expect(savedUser.fbId).to.equal(u.fbId);
expect(savedUser.fbName).to.equal(u.fbName);
expect(savedUser.gender).to.equal(u.gender);
expect(savedUser.birthdate).to.equal(u.birthdate);
expect(savedUser.aboutMe).to.equal(u.aboutMe);
</code>```

I want to verify these conditions in multiple tests for different objects.

I've tried to isolate these expects in a helper utility module before, but although there were intermediary mentions of failed expects half way, these tests didn't actually indicate failure at the end.

What is the better way to achieve the desired result?

答:
Just wrap them in a function.    </p>

```<code>function validateSavedUser(savedUser) {
  expect(savedUser).to.have.all.keys(['fbId', 'fbName', 'gender', 'birthdate', 'aboutMe']);
  expect(savedUser.fbId).to.equal(u.fbId);
  expect(savedUser.fbName).to.equal(u.fbName);
  expect(savedUser.gender).to.equal(u.gender);
  expect(savedUser.birthdate).to.equal(u.birthdate);
  expect(savedUser.aboutMe).to.equal(u.aboutMe);
}
</code>```

Title: chai reuse series of expects

Body:
How do I reuse a series of expects?
For example:

expect(savedUser).to.have.all.keys(['fbId', 'fbName', 'gender', 'birthdate', 'aboutMe']);
expect(savedUser.fbId).to.equal(u.fbId);
expect(savedUser.fbName).to.equal(u.fbName);
expect(savedUser.gender).to.equal(u.gender);
expect(savedUser.birthdate).to.equal(u.birthdate);
expect(savedUser.aboutMe).to.equal(u.aboutMe);

I want to verify these conditions in multiple tests for different objects.

I've tried to isolate these expects in a helper utility module before, but although there were intermediary mentions of failed expects half way, these tests didn't actually indicate failure at the end.

What is the better way to achieve the desired result?

Body:
Just wrap them in a function.

function validateSavedUser(savedUser) {
  expect(savedUser).to.have.all.keys(['fbId', 'fbName', 'gender', 'birthdate', 'aboutMe']);
  expect(savedUser.fbId).to.equal(u.fbId);
  expect(savedUser.fbName).to.equal(u.fbName);
  expect(savedUser.gender).to.equal(u.gender);
  expect(savedUser.birthdate).to.equal(u.birthdate);
  expect(savedUser.aboutMe).to.equal(u.aboutMe);
}


问:
AWS DynamoDB data with and/or without types?
I'm using the aws-sdk for NodeJS to interact with a DynamoDB table. This is my first look at DynamoDB.

When using a call like getItem() or updateItem(), the data structure includes types, like this:

```<code>{
  'a': { S: 'My string' }
}
</code>```

Is there any way to pass and receive these objects without the types..? So...

```<code>{
  'a': 'My string'
}
</code>```

Or, any helper functions already written that will convert objects to and from this format..?

```<code>const data = dbToObj({ 'a': { S: 'My string' } })
// { 'a': 'My string' }
</code>```

So I could convert to it when populating call params, and convert from it when receiving data.

Trying to avoid accessing my data like:

```<code>const myData = data.Item.something.M.somethinElse.M.qwerty.S
</code>```

I know I could write something myself, just wondering if anyone knows of functions/options already available that would do this. I couldn't find any.

答: Dynamoose is another modelling tool that can abstract even more extraneous code away. The github is here. I think its built on top of the AWS documentclient, although I haven't done much digging.</p>

Body:
I'm using the aws-sdk for NodeJS to interact with a DynamoDB table. This is my first look at DynamoDB.

When using a call like getItem() or updateItem(), the data structure includes types, like this:

{
  'a': { S: 'My string' }
}

Is there any way to pass and receive these objects without the types..? So...

{
  'a': 'My string'
}

Or, any helper functions already written that will convert objects to and from this format..?

const data = dbToObj({ 'a': { S: 'My string' } })
// { 'a': 'My string' }

So I could convert to it when populating call params, and convert from it when receiving data.

Trying to avoid accessing my data like:

const myData = data.Item.something.M.somethinElse.M.qwerty.S

I know I could write something myself, just wondering if anyone knows of functions/options already available that would do this. I couldn't find any.

ContentLicense: CC BY-SA 4.0


问:
Xamarin display list of imagesources in XAML
Is it possible to display a list of ImageSources in XAML with Xamarin like you do with an List of Strings? In string you would do:

```<code><ListView x:Name="newsList" ItemsSource="{Binding newsList}" ItemTapped="listView_ItemTapped" IsPullToRefreshEnabled="True" RefreshCommand="{Binding RefreshNewsCommand}" IsRefreshing="{Binding IsCurrentlyRefreshing}" />
</code>```

However if you do this with an list of ImageSources it will not work.
Does anyone know an appropriate way to load this list of images into my few? Preferably so that i can load them next to the items of my NewsList?

答:
Yes, you can define an "ItemTemplate" on the ListView (xaml / c#). There are 2 predefined ViewCells that you can assign to the ItemTemplate. One of them is "ImageCell". But ImageCell displays an Image + Text.

Also you might be interested in this:
https://developer.xamarin.com/guides/xamarin-forms/user-interface/listview/customizing-cell-appearance/

You will have to create a custom ViewCell.

Something like this (pseudo code):

```<code>ViewCell:

<ViewCell>
    <ViewCell.View>
        <Image Source="{Binding CoolImageSource}" />
    </ViewCell.View>
</ViewCell>

//Your ListView, bring the namespace in, to reference your viewcell
//You can also define the item directly inside of the DataTemplate
//But keep your code clean and hold the viewcells separately
<ListView xmlns:vc=YourNameSpace.ViewCellsFolder>
    <ListView.ItemTemplate>
        <DataTemplate>
            <vc:MyCoolViewCell />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

//And finally assign a List of such model:
public class ImageItem
{
    public ImageSource CoolImageSource { get; set; }
}
</code>```

Body:
Is it possible to display a list of ImageSources in XAML with Xamarin like you do with an List of Strings? In string you would do:

<ListView x:Name="newsList" ItemsSource="{Binding newsList}" ItemTapped="listView_ItemTapped" IsPullToRefreshEnabled="True" RefreshCommand="{Binding RefreshNewsCommand}" IsRefreshing="{Binding IsCurrentlyRefreshing}" />

However if you do this with an list of ImageSources it will not work.
Does anyone know an appropriate way to load this list of images into my few? Preferably so that i can load them next to the items of my NewsList?

Body:
Yes, you can define an "ItemTemplate" on the ListView (xaml / c#). There are 2 predefined ViewCells that you can assign to the ItemTemplate. One of them is "ImageCell". But ImageCell displays an Image + Text.

Also you might be interested in this:
https://developer.xamarin.com/guides/xamarin-forms/user-interface/listview/customizing-cell-appearance/

You will have to create a custom ViewCell.

Something like this (pseudo code):

ViewCell:

<ViewCell>
    <ViewCell.View>
        <Image Source="{Binding CoolImageSource}" />
    </ViewCell.View>
</ViewCell>

//Your ListView, bring the namespace in, to reference your viewcell
//You can also define the item directly inside of the DataTemplate
//But keep your code clean and hold the viewcells separately
<ListView xmlns:vc=YourNameSpace.ViewCellsFolder>
    <ListView.ItemTemplate>
        <DataTemplate>
            <vc:MyCoolViewCell />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

//And finally assign a List of such model:
public class ImageItem
{
    public ImageSource CoolImageSource { get; set; }
}


问:
Query ranges for numbers in an array
Given N input integers, and M query ranges, output the set of integers that fall within each query range (both bounds are inclusive). For example:

```<code>N = [-10, -1, -2, 0, 0, 8, 12, 16]
M = [(-100, 0), (2, 5), (13, 18)]
</code>```

The answer/output would then be:

```<code>[-10, -1, -2, 0, 0]
[]
[16]
</code>```

I've been trying to think of optimal solutions to this, and am struggling to come up with something that's better than O(N*M) at worst case. The approaches I've considered so far are:

Brute Force - For each query, check every digit in N and see if it falls within the range.

Presorted Input - Sort the input digits (O(NlogN)), and then do the above. Can do bounds checks for queries that are completely out of range, and remove the need to iterate (i.e. querying (0, 2) for a list like [5, 6, 7]). This still involves iterating though, and at worst case is still O(NM) (right?)

Hash Set - Add each value in the input array into a hash set, and then for each possible integer value within the query range, check if it exists in the hash set. This works for smaller ranges, but basically is the same thing -> it's O(MX) where X is the length of the query range. So if you have a query range that's huge (i.e. (-10000000, 10000000)), it wouldn't scale.

I would love to hear/learn about solutions that are better! (An alternative to this question is determining the # of digits that are within each query range, as opposed to outputting the digits).

Please let me know!

答:
Can be done in (2*M + N) log (2*M + N) with a sweep line algorithm

Create list of events:

number from N.

interval start from M

interval end from M

sort them by positions (in case of tie, you have to order depending of event: depend if your range are open or closed).

Then iterate over events:

if it is a start interval, add it to current opened intervals.

if it is a end interval, remove it from current opened intervals.

if it is a number from N, add it to all opened intervals.

So in your case, event list would be

```<code>{-100S -10N -2N -1N, 0N, 0N, 0E, 2S, 5E, 8N, 12N, 13S, 16N, 18E}
</code>```

-100S: modify active interval [(-100, 0)].

-10N, -2N, -1N, 0N, 0N: add it to [(-100, 0)]

-0E: active interval: []

2S: active interval: [(2, 5)]

5E: active interval: []

8N, 12N: Add it to no intervals.

13S: active interval: [(13, 18)]

16N: Add it to interval (13, 18).

18E: active interval: []

Related to:

http://stackoverflow.com/questions/4542892/possible-interview-question-how-to-find-all-overlapping-intervals

https://0fps.net/2015/01/18/collision-detection-part-2/

Title: Query ranges for numbers in an array

Body:
Given N input integers, and M query ranges, output the set of integers that fall within each query range (both bounds are inclusive). For example:

N = [-10, -1, -2, 0, 0, 8, 12, 16]
M = [(-100, 0), (2, 5), (13, 18)]

The answer/output would then be:

[-10, -1, -2, 0, 0]
[]
[16]

I've been trying to think of optimal solutions to this, and am struggling to come up with something that's better than O(N*M) at worst case. The approaches I've considered so far are:

Brute Force - For each query, check every digit in N and see if it falls within the range.

Presorted Input - Sort the input digits (O(NlogN)), and then do the above. Can do bounds checks for queries that are completely out of range, and remove the need to iterate (i.e. querying (0, 2) for a list like [5, 6, 7]). This still involves iterating though, and at worst case is still O(NM) (right?)

Hash Set - Add each value in the input array into a hash set, and then for each possible integer value within the query range, check if it exists in the hash set. This works for smaller ranges, but basically is the same thing -> it's O(MX) where X is the length of the query range. So if you have a query range that's huge (i.e. (-10000000, 10000000)), it wouldn't scale.

I would love to hear/learn about solutions that are better! (An alternative to this question is determining the # of digits that are within each query range, as opposed to outputting the digits).

Please let me know!

Body:
Can be done in (2*M + N) log (2*M + N) with a sweep line algorithm

Create list of events:

number from N.

interval start from M

interval end from M

sort them by positions (in case of tie, you have to order depending of event: depend if your range are open or closed).

Then iterate over events:

if it is a start interval, add it to current opened intervals.

if it is a end interval, remove it from current opened intervals.

if it is a number from N, add it to all opened intervals.

So in your case, event list would be

{-100S -10N -2N -1N, 0N, 0N, 0E, 2S, 5E, 8N, 12N, 13S, 16N, 18E}

-100S: modify active interval [(-100, 0)].

-10N, -2N, -1N, 0N, 0N: add it to [(-100, 0)]

-0E: active interval: []

2S: active interval: [(2, 5)]

5E: active interval: []

8N, 12N: Add it to no intervals.

13S: active interval: [(13, 18)]

16N: Add it to interval (13, 18).

18E: active interval: []

Related to:

http://stackoverflow.com/questions/4542892/possible-interview-question-how-to-find-all-overlapping-intervals

https://0fps.net/2015/01/18/collision-detection-part-2/


问:
getting a random value of object property and storing to variable
I am trying to get a random value from the object property by comparing properties to the value I get from list item by .text(). I try to store the result to a span after that.

I am trying to find first property of either tv or animals (or any other if added in the future) and then property of either easy, medium or hard

Not sure if the function displayWord is correct or maybe I am missing something else.

Here is some other relevant parts of the code to see what variables referring to. https://jsfiddle.net/peliudzemas/0fqbgo9k/1/

let result = "";
let charadesList = {
  tv : {
    easy : ['Harry Potter', 'James Bond', 'transformers'],
    medium : ['the planet of The Apes', 'Inception', 'finding nemo'],
    hard : ['taken', 'alladin', 'cast away', 'schindler\'s list']
          },

  animals : {
    easy : ['chicken', 'mouse', 'dog'],
    medium : ['lion', 'elephant', 'giraffe'],
    hard : ['monkey', 'panda', 'mole']
  }
}

function displayWord(obj, value1, value2) {
  for (var p in obj) {
    if (obj.p == value1) {
      for (var pp in obj.p) {
        if (obj.p.pp == value2) {
          result += obj.p.pp[Math.floor(Math.random()*obj.p.pp.length)];
        }
      }
    }
  }
  $('#word').append(result);
}
$(document).ready(function () {
   displayWord(charadesList, selectCategory, selectLevel);
});```

答:
Not sure what you are trying to do, but if you know what props you looking for use - in the above example you know - this:</p>

```<code>function getRandomWord(obj,val1,val2) {
    try {
        return obj[val1][val2][Math.floor(Math.random() * obj[val1][val2].length)];
    } catch {
        return null;
    }
}

function {
    let randomWord = getRandomWord(...params)
    if (randomWord)
        $('#word').append(result);
}
</code>```

Body:
Not sure what you are trying to do, but if you know what props you looking for use - in the above example you know - this:

function getRandomWord(obj,val1,val2) {
    try {
        return obj[val1][val2][Math.floor(Math.random() * obj[val1][val2].length)];
    } catch {
        return null;
    }
}

function {
    let randomWord = getRandomWord(...params)
    if (randomWord)
        $('#word').append(result);
}


问:
How to create Entity Class for multiple table joins
I am developing a spring boot application, i need a proper design help for one of my entity relation.

These are my tables

```<code>DROP TABLE IF EXISTS user;
CREATE TABLE user
(
 User_ID   INT AUTO_INCREMENT PRIMARY KEY,
 Email     VARCHAR(1024),
 Phone     BIGINT,
 Password  VARCHAR(128),
 User_Type ENUM ('TEACHER', 'PARENT'),
 Status    ENUM ('ACTIVE', 'DEACTIVE', 'SUSPENDED')
 );

DROP TABLE IF EXISTS teacher;
CREATE TABLE teacher
(
   Teacher_ID      INT AUTO_INCREMENT PRIMARY KEY,
   Name            VARCHAR(1024),
   Email           VARCHAR(1024),
   Phone           BIGINT,
   Gender          ENUM (0, 1),
   Date_Of_Joining INT,
   Designation     VARCHAR(1024),
   Is_Active       INT
);

DROP TABLE IF EXISTS parent;
CREATE TABLE parent
(
  Parent_ID  INT AUTO_INCREMENT PRIMARY KEY,
  Name       VARCHAR(1024),
  Email      VARCHAR(1024),
  Phone      BIGINT,
  Occupation VARCHAR(1024),
  Address    VARCHAR(4048)
);

DROP TABLE IF EXISTS student;
CREATE TABLE student
(
  Student_ID    INT AUTO_INCREMENT PRIMARY KEY,
  Student_Name  VARCHAR(1024),
  Class         VARCHAR(16),
  Section       VARCHAR(16),
  Academic_Year VARCHAR(64),
  DOB           DATE,
  Gender        ENUM (0, 1),
  Parent_ID     INT
);
</code>```

Can anyone please help me creating entity classes for the same. Based on the type of user in user table i need to join with either teacher or parent table. For example if User_Type is TEACHER then i will join with teacher table else i will join user with parent table. Join condition would be email.

Student table has one to one relationship with parent table.

答:
You can create domain models like this </p>

```<code>@Entity
@Inheritance(strategy= InheritanceType.JOINED)
public User{

    //properties

}

@Entity
@PrimaryKeyJoinColumn(name = "id")
public  Teacher extends User{

    //properties

}

@Entity
public Parent extends User{

   //properties
}

@Entity
public Students {

    @GenericGenerator(name = "generator", strategy = "foreign",parameters = @Parameter(name = "property", value = "stock"))
    @Id
    @GeneratedValue(generator = "generator")
    @Column(name = "Parent_ID", unique = true, nullable = false)
    private Integer id;

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    public Parent parent;
}
</code>```

Body:
I am developing a spring boot application, i need a proper design help for one of my entity relation.

These are my tables

DROP TABLE IF EXISTS user;
CREATE TABLE user
(
 User_ID   INT AUTO_INCREMENT PRIMARY KEY,
 Email     VARCHAR(1024),
 Phone     BIGINT,
 Password  VARCHAR(128),
 User_Type ENUM ('TEACHER', 'PARENT'),
 Status    ENUM ('ACTIVE', 'DEACTIVE', 'SUSPENDED')
 );

DROP TABLE IF EXISTS teacher;
CREATE TABLE teacher
(
   Teacher_ID      INT AUTO_INCREMENT PRIMARY KEY,
   Name            VARCHAR(1024),
   Email           VARCHAR(1024),
   Phone           BIGINT,
   Gender          ENUM (0, 1),
   Date_Of_Joining INT,
   Designation     VARCHAR(1024),
   Is_Active       INT
);

DROP TABLE IF EXISTS parent;
CREATE TABLE parent
(
  Parent_ID  INT AUTO_INCREMENT PRIMARY KEY,
  Name       VARCHAR(1024),
  Email      VARCHAR(1024),
  Phone      BIGINT,
  Occupation VARCHAR(1024),
  Address    VARCHAR(4048)
);

DROP TABLE IF EXISTS student;
CREATE TABLE student
(
  Student_ID    INT AUTO_INCREMENT PRIMARY KEY,
  Student_Name  VARCHAR(1024),
  Class         VARCHAR(16),
  Section       VARCHAR(16),
  Academic_Year VARCHAR(64),
  DOB           DATE,
  Gender        ENUM (0, 1),
  Parent_ID     INT
);

Can anyone please help me creating entity classes for the same. Based on the type of user in user table i need to join with either teacher or parent table. For example if User_Type is TEACHER then i will join with teacher table else i will join user with parent table. Join condition would be email.

Student table has one to one relationship with parent table.

Body:
You can create domain models like this

@Entity
@Inheritance(strategy= InheritanceType.JOINED)
public User{

    //properties

}

@Entity
@PrimaryKeyJoinColumn(name = "id")
public  Teacher extends User{

    //properties

}

@Entity
public Parent extends User{

   //properties
}

@Entity
public Students {

    @GenericGenerator(name = "generator", strategy = "foreign",parameters = @Parameter(name = "property", value = "stock"))
    @Id
    @GeneratedValue(generator = "generator")
    @Column(name = "Parent_ID", unique = true, nullable = false)
    private Integer id;

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    public Parent parent;
}


问:
Why is my Rails instance variable nil in my view?
I am stuck on someothing probably incredibly stupid, but I can't find my problem.  I'm using Rails 3.0.3, and ruby 1.9.2 on a ubuntu machine.

I am trying to just set an instance variable in my controller, and use it to create a form on a new view template, yet it is coming up nil in my view.   I know that instance variables set in the controller are supposed to be copied to the view, but here its set to nil.  Can anyone see what I'm doing wrong?  Here is my error message:

```<code>NoMethodError in Urls#new

undefined method `model_name' for NilClass:Class

Extracted source (around line #1):

1: <%= form_for @url do |f| %>
2:    <%= f.submit %>
3: <% end %>
</code>```

app/controllers/urls_controller.rb

```<code>class UrlsController < ApplicationController
  def new
    @url = Url.new
  end
end
</code>```

app/views/urls/new.html.erb

```<code><%= form_for @url do |f| %>
   <%= f.submit %>
<% end %>
</code>```

app/models/url.rb

```<code># == Schema Information
# Schema version: 20110122002326
#
# Table name: urls
#
#  id         :integer         not null, primary key
#  long_url   :text
#  short_url  :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class Url < ActiveRecord::Base
end
</code>```

app/controllers/application_controller.rb

```<code>class ApplicationController < ActionController::Base
  protect_from_forgery
end
</code>```

答:
Url is a reserved word I'm afraid.

http://wiki.rubyonrails.org/rails/pages/reservedwords

ContentLicense: CC BY-SA 2.5

Body:
I am stuck on someothing probably incredibly stupid, but I can't find my problem.  I'm using Rails 3.0.3, and ruby 1.9.2 on a ubuntu machine.

I am trying to just set an instance variable in my controller, and use it to create a form on a new view template, yet it is coming up nil in my view.   I know that instance variables set in the controller are supposed to be copied to the view, but here its set to nil.  Can anyone see what I'm doing wrong?  Here is my error message:

NoMethodError in Urls#new

undefined method `model_name' for NilClass:Class

Extracted source (around line #1):

1: <%= form_for @url do |f| %>
2:    <%= f.submit %>
3: <% end %>

app/controllers/urls_controller.rb

class UrlsController < ApplicationController
  def new
    @url = Url.new
  end
end

app/views/urls/new.html.erb

<%= form_for @url do |f| %>
   <%= f.submit %>
<% end %>

app/models/url.rb

# == Schema Information
# Schema version: 20110122002326
#
# Table name: urls
#
#  id         :integer         not null, primary key
#  long_url   :text
#  short_url  :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class Url < ActiveRecord::Base
end

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
end


问:
Serializing double to an int within POJO
I am having trouble figuring out how to serialize my a double to an int in my POJO. At the moment, I am sloppily making the conversion within the setter method. The double will always be between 0 and 1. Below are the getter and setter methods within my POJO:

```<code>@JsonProperty("costMargin")
public int getCostMargin() {
    return costMargin;
}

@JsonProperty("costMargin")
public void setCostMargin(double costMargin) {
        this.costMargin = (int)(Math.round(costMargin * 100));
}
</code>```

Can anyone help me figure out how to serialize this double to an int, without making the conversion within the setter method? I am trying to look into other ways of doing this, such as creating a serializer class, and including an annotation in my Pojo. for example: @JsonSerialize(using = CustomDoubleSerializer.class)

答:
Answer is: you cannot do it.

You have to convert double to int somewhere by truncating or rounding somehow.

In your code you just violate Java Bean specification. Getter returns int, but Setter has double as parameter.

If so, you have to convert in setter. Otherwise you have to do it in the caller before call a setter.

Body:
I am having trouble figuring out how to serialize my a double to an int in my POJO. At the moment, I am sloppily making the conversion within the setter method. The double will always be between 0 and 1. Below are the getter and setter methods within my POJO:

@JsonProperty("costMargin")
public int getCostMargin() {
    return costMargin;
}

@JsonProperty("costMargin")
public void setCostMargin(double costMargin) {
        this.costMargin = (int)(Math.round(costMargin * 100));
}

Can anyone help me figure out how to serialize this double to an int, without making the conversion within the setter method? I am trying to look into other ways of doing this, such as creating a serializer class, and including an annotation in my Pojo. for example: @JsonSerialize(using = CustomDoubleSerializer.class)


问:
Symfony 3 jquery-ui datepicker
I'm trying to understand forms in Symfony and I have to realize the field DateType.

My layout:

```<code><div class="col-sm-10">
    <input name="{{ form.date.vars.full_name }}" id="js-datepicker" value="{{ form.date.vars.value }}" type="text" placeholder="Например: 12/11/2018 " class="form-control input-lg m-b">
    <div class="form-errors text-danger">
        {{ form_errors(form.date) }}
    </div>
</div>
   <script>
    $( function() {
         $( "#js-datepicker" ).datepicker({
             format: 'dd/MM/yyyy'
         });
    });
</script>
</code>```

My controller

```<code>$form = $this->createFormBuilder($client)
        ->add('date', DateType::class)
        ->getForm();
</code>```

My Entity

```<code> /**
 * @ORM\Column(type="datetime")
 *
 * @var \DateTime $date
 */
 protected $date;
</code>```

And I have a trouble. When I tried to run it I have this error.

```<code>An exception has been thrown during the rendering of a template ("Notice: Array to string conversion").
</code>```

But I cannot understand where my mistake. Help me, please! Thank you!

UPDATE:
I redecorate my twig code:

```<code>{% for formInput in form %}
    {{ form_label(formInput) }}
    <div class="col-sm-10">
        {{ form_widget(formInput) }}
    </div>
    <div class="form-errors text-danger">
        {{ form_errors(formInput) }}
    </div>
{% endfor %}
</code>```

And my controller:

```<code>    $formLabelAttr = 'col-sm-2 control-label';
    $formInputAttr = 'col-sm-10 form-control input-lg m-b';

    $form = $this->createFormBuilder($client)
        ->add('fullName', TextType::class, [
            'label' => 'Имя',
            'label_attr' => [
                'class' => $formLabelAttr,
            ],
            'attr' => [
                'placeholder' => 'Например: Иванов Иван Иванович',
                'class' => $formInputAttr,
            ],
        ])
        ->add('date', DateType::class, [
            'label' => 'Дата проведения',
            'label_attr' => [
                'class' => $formLabelAttr,
            ],
            'attr' => [
                'placeholder' => 'Например: 12/12/2020',
                'class' => $formInputAttr,
            ],
            'widget' => 'single_text',
            'format' => 'dd-MM-yyyy',
        ])
        ->add('diplomaNumber', HiddenType::class, ['data' => random_int(1, 200)])
        ->getForm();
</code>```

Now, I have two problems:
1. I can observe the form__token label in the page (label) at the bottom of the form.
2. I can't submit form because I have the error in DateType field (Value is not valid).
What's wrong?

答:
You need to add a date filter.

{{ xxx_your_date_field|date("m/d/Y") }}

more details twig date

also in your formType use single_text. more details Rendering a single HTML5 Textbox

Title: Symfony 3 jquery-ui datepicker

Body:
I'm trying to understand forms in Symfony and I have to realize the field DateType.

My layout:

    <input name="{{ form.date.vars.full_name }}" id="js-datepicker" value="{{ form.date.vars.value }}" type="text" placeholder="Например: 12/11/2018 " class="form-control input-lg m-b">

        {{ form_errors(form.date) }}

My controller

$form = $this->createFormBuilder($client)
        ->add('date', DateType::class)
        ->getForm();

My Entity

 /**
 * @ORM\Column(type="datetime")
 *
 * @var \DateTime $date
 */
 protected $date;

And I have a trouble. When I tried to run it I have this error.

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion").

But I cannot understand where my mistake. Help me, please! Thank you!

UPDATE:
I redecorate my twig code:

{% for formInput in form %}
    {{ form_label(formInput) }}

        {{ form_widget(formInput) }}

        {{ form_errors(formInput) }}

{% endfor %}

And my controller:

    $formLabelAttr = 'col-sm-2 control-label';
    $formInputAttr = 'col-sm-10 form-control input-lg m-b';

    $form = $this->createFormBuilder($client)
        ->add('fullName', TextType::class, [
            'label' => 'Имя',
            'label_attr' => [
                'class' => $formLabelAttr,
            ],
            'attr' => [
                'placeholder' => 'Например: Иванов Иван Иванович',
                'class' => $formInputAttr,
            ],
        ])
        ->add('date', DateType::class, [
            'label' => 'Дата проведения',
            'label_attr' => [
                'class' => $formLabelAttr,
            ],
            'attr' => [
                'placeholder' => 'Например: 12/12/2020',
                'class' => $formInputAttr,
            ],
            'widget' => 'single_text',
            'format' => 'dd-MM-yyyy',
        ])
        ->add('diplomaNumber', HiddenType::class, ['data' => random_int(1, 200)])
        ->getForm();

Now, I have two problems:
1. I can observe the form__token label in the page (label) at the bottom of the form.
2. I can't submit form because I have the error in DateType field (Value is not valid).
What's wrong?


问:
Rails 3, comparing only the dates of two datetime columns in rails
Lets say I want to compare the dates only of two datetime columns within 1 record. So I don't want the time looked at.

I.e.

viewed_date, and updated_at (I added viewed_date) are two datetime formats, but I only want to see if they occurred on the same day or days apart. The problem with datetime is that its comparing the times, which is just too specific for me right now.

Thanks

-Elliot

答:
Declare a new attribute that contains just the date:

```<code>class WhateverModel < ActiveRecord::Base
  ...
  def viewed_date_only
    viewed_date.to_date
  end
end
</code>```

Use that for your comparison in the controller or wherever.

Body:
Declare a new attribute that contains just the date:

class WhateverModel < ActiveRecord::Base
  ...
  def viewed_date_only
    viewed_date.to_date
  end
end

Use that for your comparison in the controller or wherever.


问:
Saving x, and y from `curve()` in a for loop R?
I have a function called all.priors (see R code below). My goal is to get the x and y from the curve() call inside the for loop, and save these xs and ys as object h.

(I want to have 101 rows, and 2*length(d) columns in h. This way, each 2 columns, contain x and y from a curve() run in the for loop.)

Question:

how can I correctly save the xs and ys from the curve() call? [I get the error: incorrect number of subscripts on matrix]

```<code>all.priors = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

h = matrix(NA, 101, 2*length(d))

for(i in 1:length(d)){
         p = function(x) get(d[i])(x, a, b)
     prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
likelihood = function(x) dbinom(Bi, n, x)
 posterior = function(x) prior(x)*likelihood(x)
     h[i,] = curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n")
     }
}
#Example of use:
all.priors(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dlogis"))
</code>```

答:
A different way to solve this might be to save the answers in a list rather than a matrix. I think that your function complicates the picture of what is going on,  so I will use a simpler example. </p>

```<code>h = list()
for(i in 1:5) {
    h[i] = list(curve(sin(i*x), xlim=c(0,6.3))) }
</code>```

<p>The resulting data structure should be easy to use. </p>

Body:
I have a function called all.priors (see R code below). My goal is to get the x and y from the curve() call inside the for loop, and save these xs and ys as object h.

(I want to have 101 rows, and 2*length(d) columns in h. This way, each 2 columns, contain x and y from a curve() run in the for loop.)

Question:

how can I correctly save the xs and ys from the curve() call? [I get the error: incorrect number of subscripts on matrix]

all.priors = function(a, b, lo, hi, d, Bi = 55, n = 1e2){

h = matrix(NA, 101, 2*length(d))

for(i in 1:length(d)){
         p = function(x) get(d[i])(x, a, b)
     prior = function(x) p(x)/integrate(p, lo, hi)[[1]]
likelihood = function(x) dbinom(Bi, n, x)
 posterior = function(x) prior(x)*likelihood(x)
     h[i,] = curve(posterior, ty = "n", ann = FALSE, yaxt = "n", xaxt = "n", add = i!= 1, bty = "n")
     }
}
#Example of use:
all.priors(lo = 0, hi = 1, a = 2, b = 3, d = c("dgamma", "dnorm", "dcauchy", "dlogis"))

Body:
A different way to solve this might be to save the answers in a list rather than a matrix. I think that your function complicates the picture of what is going on,  so I will use a simpler example.

h = list()
for(i in 1:5) {
    h[i] = list(curve(sin(i*x), xlim=c(0,6.3))) }

The resulting data structure should be easy to use.


问:
update a single record for 200 concurrent user in postgres
I have a single record containing the version, initially 1.
200 concurrent users are updating the same record, every update version should increase by 1.if everything goes proper, then version must be 200.

I am unable to update the record properly.

```<code>Max connection pool size = 50
Database = Postgres
</code>```

Could you please suggest?
Thanks in Advance :)

答:
There is no need for anything complicated here, and no need for explicit transactions management.

All involved sessions just issue

```<code>UPDATE mytab
SET version=version+1
WHERE key=42
RETURNING version;
</code>```

By default each statement runs in its own transaction, and these transactions will lock each other out with an exclusive lock on the row, so they will be serialized automatically.

Body:
I have a single record containing the version, initially 1.
200 concurrent users are updating the same record, every update version should increase by 1.if everything goes proper, then version must be 200.

I am unable to update the record properly.

Max connection pool size = 50
Database = Postgres

Could you please suggest?
Thanks in Advance :)

Body:
There is no need for anything complicated here, and no need for explicit transactions management.

All involved sessions just issue

UPDATE mytab
SET version=version+1
WHERE key=42
RETURNING version;

By default each statement runs in its own transaction, and these transactions will lock each other out with an exclusive lock on the row, so they will be serialized automatically.


问:
How to get this link to start in another folder?
I have a batch script that creates a vbs that creates a shortcut (complicated I know), however the problem is that it launches the program where the shortcut is located. Any way to make it start in C:\users\Public\Settings\ where the exe is? Thanks everyone!</p>

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
SET LinkName=ITCMD-Notifier-Settings
SET Esc_LinkDest=C:\Users\%username%\Desktop\!LinkName!.lnk
SET Esc_LinkTarget=C:\users\Public\ITCMD\Settings\ITCMD Notifier Settings.exe
SET cSctVBS=CreateShortcut.vbs
SET LOG=".\%~N0_runtime.log"
((
  echo Set oWS = WScript.CreateObject^("WScript.Shell"^)
  echo sLinkFile = oWS.ExpandEnvironmentStrings^("!Esc_LinkDest!"^)
  echo Set oLink = oWS.CreateShortcut^(sLinkFile^)
  echo oLink.TargetPath = oWS.ExpandEnvironmentStrings^("!Esc_LinkTarget!"^)
  echo oLink.Save
)1>!cSctVBS!
cscript //nologo .\!cSctVBS!
DEL !cSctVBS! /f /q
)1>>!LOG! 2>>&1
</code>```

答:
```<code> )1>!cSctVBS!
SET "originaldir=!CD!"
PUSHD %Esc_LinkTarget%
cscript //nologo "!originaldir!\!cSctVBS!"
POPD
DEL !cSctVBS! /f /q
</code>```

No guarantee, naturally. Should save the original directory name, then switch to the executable's directory, then switch back before deleting the file.

I've included quotes around the cscript target in case the current directory contains separators. I've no notion of how cscript would see that...

Another possibility would be to switch to the executable's directory first just before the echoes which create the VBS file, then pop back after deleting that file.

Body:
I have a batch script that creates a vbs that creates a shortcut (complicated I know), however the problem is that it launches the program where the shortcut is located. Any way to make it start in C:\users\Public\Settings\ where the exe is? Thanks everyone!

SETLOCAL ENABLEDELAYEDEXPANSION
SET LinkName=ITCMD-Notifier-Settings
SET Esc_LinkDest=C:\Users\%username%\Desktop\!LinkName!.lnk
SET Esc_LinkTarget=C:\users\Public\ITCMD\Settings\ITCMD Notifier Settings.exe
SET cSctVBS=CreateShortcut.vbs
SET LOG=".\%~N0_runtime.log"
((
  echo Set oWS = WScript.CreateObject^("WScript.Shell"^)
  echo sLinkFile = oWS.ExpandEnvironmentStrings^("!Esc_LinkDest!"^)
  echo Set oLink = oWS.CreateShortcut^(sLinkFile^)
  echo oLink.TargetPath = oWS.ExpandEnvironmentStrings^("!Esc_LinkTarget!"^)
  echo oLink.Save
)1>!cSctVBS!
cscript //nologo .\!cSctVBS!
DEL !cSctVBS! /f /q
)1>>!LOG! 2>>&1

Body:
 )1>!cSctVBS!
SET "originaldir=!CD!"
PUSHD %Esc_LinkTarget%
cscript //nologo "!originaldir!\!cSctVBS!"
POPD
DEL !cSctVBS! /f /q

No guarantee, naturally. Should save the original directory name, then switch to the executable's directory, then switch back before deleting the file.

I've included quotes around the cscript target in case the current directory contains separators. I've no notion of how cscript would see that...

Another possibility would be to switch to the executable's directory first just before the echoes which create the VBS file, then pop back after deleting that file.


问:
Change button text on click
So, I followed an online course from www.code.org to accomodate myself with JavaScript. I used elements such as setProperty(); and onEvent();. I used an online editor to add a button and the following code to change the button's text when the user clicks it:

```<code>onEvent("button1","click", function()
 {
  setProperty("button1","text","Hello there!");
 });
</code>```

My question is: How can I do this thing in HTML, by using the <button> tag?

答:
You can add id to your button, for example:

```<code><button id="myButton">Click!</button>
</code>```

And then in javascript:

select the element.

document.getElementById("myButton");
```

<ol start="2">
<li>add the event handler to it, so the code would become like this:</li>
</ol>

<pre class="lang-js prettyprint-override"><code>document.getElementById("myButton").onclick = function() {
     myFunction()
};
</code>```

describe the event

function myFunction() {
    document.getElementById("myButton").innerHTML = "YOU CLICKED ME!";
}
```

Title: Change button text on click

Body:
So, I followed an online course from www.code.org to accomodate myself with JavaScript. I used elements such as setProperty(); and onEvent();. I used an online editor to add a button and the following code to change the button's text when the user clicks it:

onEvent("button1","click", function()
 {
  setProperty("button1","text","Hello there!");
 });

My question is: How can I do this thing in HTML, by using the <button> tag?

Body:
You can add id to your button, for example:

<button id="myButton">Click!</button>

And then in javascript:

select the element.

document.getElementById("myButton");

add the event handler to it, so the code would become like this:

document.getElementById("myButton").onclick = function() {
     myFunction()
};

describe the event

function myFunction() {
    document.getElementById("myButton").innerHTML = "YOU CLICKED ME!";
}


问:
MATLAB fwrite\fread issue: two variables are being concatenated
I am reading in a binary EDF file and I have to split it into multiple smaller EDF files at specific points and then adjust some of the values inside. Overall it works quite well but when I read in the file it combines 2 character arrays with each other. Obviously everything afterwords gets corrupted as well. I am at a dead end and have no idea what I'm doing wrong.

The part of the code (writing) that has to contain the problem:

```<code>byt=fread(fid,8,'*char');
fwrite(tfid,byt,'*char');

fwrite(tfid,fread(fid,44));
%new number of records
s = records;
fwrite(tfid,s,'*char');
fseek(fid,8,0);
%test
fwrite(tfid,fread(fid,8,'*char'),'*char');
</code>```

When I use the reader it combines the records (fwrite(tfid,s,'*char'))
with the value of the next variable. All variables before this are displayed correctly. The relevant code of the reader:

```<code>hdr.bytes      = str2double(fread(fid,8,'*char')');
reserved       = fread(fid,44);%#ok
hdr.records    = str2double(fread(fid,8,'*char')');
if hdr.records == -1
    beep
    disp('There appears to be a problem with this file; it returns an out-of-spec value of -1 for ''numberOfRecords.''')
    disp('Attempting to read the file with ''edfReadUntilDone'' instead....');
    [hdr, record] = edfreadUntilDone(fname, varargin);
    return
end
hdr.duration   = str2double(fread(fid,8,'*char')');
</code>```

答:
The likely problem is that your character array s does not have 8 characters in it, but you expect there to be 8 when you read it from the file. Whatever the number of characters in the array is, that's how many values fwrite will write out to the file. Anything less than 8 characters and you'll end up reading part of the next piece of data when you read from the file.

One fix would be to pad s with blanks before writing it:

```<code>s = [blanks(8-numel(records)) records];
</code>```

In addition, the syntax '*char' is only valid when using fread: the * indicates that the output class should be 'char' as well. It's unnecessary when using fwrite.

Body:
I am reading in a binary EDF file and I have to split it into multiple smaller EDF files at specific points and then adjust some of the values inside. Overall it works quite well but when I read in the file it combines 2 character arrays with each other. Obviously everything afterwords gets corrupted as well. I am at a dead end and have no idea what I'm doing wrong.

The part of the code (writing) that has to contain the problem:

byt=fread(fid,8,'*char');
fwrite(tfid,byt,'*char');

fwrite(tfid,fread(fid,44));
%new number of records
s = records;
fwrite(tfid,s,'*char');
fseek(fid,8,0);
%test
fwrite(tfid,fread(fid,8,'*char'),'*char');

When I use the reader it combines the records (fwrite(tfid,s,'*char'))
with the value of the next variable. All variables before this are displayed correctly. The relevant code of the reader:

hdr.bytes      = str2double(fread(fid,8,'*char')');
reserved       = fread(fid,44);%#ok
hdr.records    = str2double(fread(fid,8,'*char')');
if hdr.records == -1
    beep
    disp('There appears to be a problem with this file; it returns an out-of-spec value of -1 for ''numberOfRecords.''')
    disp('Attempting to read the file with ''edfReadUntilDone'' instead....');
    [hdr, record] = edfreadUntilDone(fname, varargin);
    return
end
hdr.duration   = str2double(fread(fid,8,'*char')');

Body:
The likely problem is that your character array s does not have 8 characters in it, but you expect there to be 8 when you read it from the file. Whatever the number of characters in the array is, that's how many values fwrite will write out to the file. Anything less than 8 characters and you'll end up reading part of the next piece of data when you read from the file.

One fix would be to pad s with blanks before writing it:

s = [blanks(8-numel(records)) records];

In addition, the syntax '*char' is only valid when using fread: the * indicates that the output class should be 'char' as well. It's unnecessary when using fwrite.


问:
C++ polymorphic ring buffer
Is there a library that would allow me to store objects of common base type in a buffer supporting enqueue and dequeue? That's really all I need, I don't need O(1) access to each element. It would be allowed that each object can have a different size (a polymorphic ring buffer).
I could use vector of pointers of base type, but that seems to me as an overkill. If I use this sort of a ring buffer, I won't have to allocate separate memory for each object.

答:
You may use Boost.Circular Buffer. Instead of int in example you may store pointers YourInterfaceClass* or std::shared_ptr< YourInterfaceClass >.

```<code>// Create a circular buffer with a capacity for 3 integers.
boost::circular_buffer<int> cb(3);

// Insert threee elements into the buffer.
cb.push_back(1);
cb.push_back(2);
cb.push_back(3);

int a = cb[0];  // a == 1
int b = cb[1];  // b == 2
int c = cb[2];  // c == 3

// The buffer is full now, so pushing subsequent
// elements will overwrite the front-most elements.

cb.push_back(4);  // Overwrite 1 with 4.
cb.push_back(5);  // Overwrite 2 with 5.

// The buffer now contains 3, 4 and 5.
a = cb[0];  // a == 3
b = cb[1];  // b == 4
c = cb[2];  // c == 5

// Elements can be popped from either the front or the back.
cb.pop_back();  // 5 is removed.
cb.pop_front(); // 3 is removed.

// Leaving only one element with value = 4.
int d = cb[0];  // d == 4
</code>```

I have used it in my project and did not have any problems with it.

Title: C++ polymorphic ring buffer

Body:
You may use Boost.Circular Buffer. Instead of int in example you may store pointers YourInterfaceClass* or std::shared_ptr< YourInterfaceClass >.

// Create a circular buffer with a capacity for 3 integers.
boost::circular_buffer<int> cb(3);

// Insert threee elements into the buffer.
cb.push_back(1);
cb.push_back(2);
cb.push_back(3);

int a = cb[0];  // a == 1
int b = cb[1];  // b == 2
int c = cb[2];  // c == 3

// The buffer is full now, so pushing subsequent
// elements will overwrite the front-most elements.

cb.push_back(4);  // Overwrite 1 with 4.
cb.push_back(5);  // Overwrite 2 with 5.

// The buffer now contains 3, 4 and 5.
a = cb[0];  // a == 3
b = cb[1];  // b == 4
c = cb[2];  // c == 5

// Elements can be popped from either the front or the back.
cb.pop_back();  // 5 is removed.
cb.pop_front(); // 3 is removed.

// Leaving only one element with value = 4.
int d = cb[0];  // d == 4

I have used it in my project and did not have any problems with it.


问:
NHibernate - one-to-one Cascade Settings
I have a one-to-one relationship between a Person class and an Employee. I  expect the INSERT to cascade from the Person to the Employee. However, this does not happen. I've tried cascade='all' and cascade='save-update' on one-to-one relationship element, but it didn't work.

The structures of the my objects are as follows:

```<code>public class Person
{
    public virtual Employee Employee { get; set; }
    public virtual int Age { get; set; }
    public virtual string Forename { get; set; }
    public virtual string Surname { get; set; }
    public virtual int PersonID { get; set; }
}

public class Employee
{
    public virtual int PersonID { get; set; }
    public virtual string PayRollNo { get; set; }
    public virtual int Holidays { get; set; }
    public virtual Person Person { get; set; }
}
</code>```

Mapping files shown below:

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Employee, Employee.DAL" table="`Employee`"  >
    <id name="PersonID" column="`PersonId`" type="int">
      <generator class="native" />
    </id>
    <property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
    <property type="int" name="Holidays" column="`Holidays`" />
    <one-to-one name="Person"  class="Person" cascade="all"/>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Person, Employee.DAL" table="`Person`"  >
    <id name="PersonID" column="`PersonId`">
      <generator class="foreign">
        <param name="property" >Employee</param>
      </generator>
    </id>
    <property type="string" name="Forename" column="`Forename`" />
    <property type="string" name="Surname" column="`Surname`" />
    <property type="int" name="Age" column="`Age`" />
    <one-to-one name="Employee" class="Employee"  constrained="true"  />
  </class>
</hibernate-mapping>
</code>```

Code for initiating the objects and saving them:

```<code>var employee = new Employee();

    employee.Person = new Person { Employee = employee };

    ISessionFactory sessionFactory = (new Configuration()).Configure().BuildSessionFactory();

    employee.Person.Age = 27;
    employee.Person.Forename = "N";
    employee.Person.Surname = "M";

    employee.PayRollNo = "12";
    employee.Holidays = 27;

    using (var session = sessionFactory.OpenSession())
    {
        session.Save(employee);
    }
</code>```

答:
Yads is essentially right. The second <one-to-one> (from Employee to Person) needs constrained="true". With that, the following code should work:

```<code>using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
    var person = new PersonDataContext();
    person.Employee = new EmployeeDataContext { Person = person };
    session.Save(person);
    tx.Commit();
}
</code>```

A few additional suggestions:

Do not use lazy="false". Read http://ayende.com/Blog/archive/2010/08/04/nhibernate-is-lazy-just-live-with-it.aspx

Use more DDD names for your classes. You have an entity that represents a Person, whose data is stored in the Person table. Why do you call it PersonDataContext?

You are mapping to properties, not fields. Show the code for your properties in your classes instead of the underlying fields.

You don't need to override with the default values. If a property's name is PayRollNo, the default column name is PayRollNo. If a property's type is int, the default mapped type is int too.

Body:
I have a one-to-one relationship between a Person class and an Employee. I  expect the INSERT to cascade from the Person to the Employee. However, this does not happen. I've tried cascade='all' and cascade='save-update' on one-to-one relationship element, but it didn't work.

The structures of the my objects are as follows:

public class Person
{
    public virtual Employee Employee { get; set; }
    public virtual int Age { get; set; }
    public virtual string Forename { get; set; }
    public virtual string Surname { get; set; }
    public virtual int PersonID { get; set; }
}

public class Employee
{
    public virtual int PersonID { get; set; }
    public virtual string PayRollNo { get; set; }
    public virtual int Holidays { get; set; }
    public virtual Person Person { get; set; }
}

Mapping files shown below:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Employee, Employee.DAL" table="`Employee`"  >
    <id name="PersonID" column="`PersonId`" type="int">
      <generator class="native" />
    </id>
    <property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
    <property type="int" name="Holidays" column="`Holidays`" />
    <one-to-one name="Person"  class="Person" cascade="all"/>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Person, Employee.DAL" table="`Person`"  >
    <id name="PersonID" column="`PersonId`">
      <generator class="foreign">
        <param name="property" >Employee</param>
      </generator>
    </id>
    <property type="string" name="Forename" column="`Forename`" />
    <property type="string" name="Surname" column="`Surname`" />
    <property type="int" name="Age" column="`Age`" />
    <one-to-one name="Employee" class="Employee"  constrained="true"  />
  </class>
</hibernate-mapping>

Code for initiating the objects and saving them:

var employee = new Employee();

    employee.Person = new Person { Employee = employee };

    ISessionFactory sessionFactory = (new Configuration()).Configure().BuildSessionFactory();

    employee.Person.Age = 27;
    employee.Person.Forename = "N";
    employee.Person.Surname = "M";

    employee.PayRollNo = "12";
    employee.Holidays = 27;

    using (var session = sessionFactory.OpenSession())
    {
        session.Save(employee);
    }

Body:
Yads is essentially right. The second <one-to-one> (from Employee to Person) needs constrained="true". With that, the following code should work:

using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
    var person = new PersonDataContext();
    person.Employee = new EmployeeDataContext { Person = person };
    session.Save(person);
    tx.Commit();
}

A few additional suggestions:

Do not use lazy="false". Read http://ayende.com/Blog/archive/2010/08/04/nhibernate-is-lazy-just-live-with-it.aspx

Use more DDD names for your classes. You have an entity that represents a Person, whose data is stored in the Person table. Why do you call it PersonDataContext?

You are mapping to properties, not fields. Show the code for your properties in your classes instead of the underlying fields.

You don't need to override with the default values. If a property's name is PayRollNo, the default column name is PayRollNo. If a property's type is int, the default mapped type is int too.


问:
Converting a date and and a char 'time' field to a single date
I am trying to concatenate two fields and load the data into a date field.

I have a table with hier_dt as DATE datatype and hier_tm as CHAR datatype, with data like:

```<code>hier_dt   | hier_tm
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
17-JAN-17 | 17:54
</code>```

I would like to concatenate both of these into a single DATE datatype field, to produce:

```<code>hier_dt_tm
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54
</code>```

Is there a way I can accomplish this?

My current query is:

```<code>select to_date(concat(to_char(NVL(hier_DT,'01-JAN-1900'), 'yyyy/mm/dd'),
  concat(' ',NVL(hier_tm,'00:00'))), 'yyyy/mm/dd hh24:mi') as temp
from XXX1
</code>```

答:
Try:

```<code> SELECT
 /* TO_DATE( */
  TO_CHAR(hier_dt, 'YYYY/MM/DD') ||
  ' ' ||
  hier_tm
 /* ,'YYYY/MM/DD HH24:MI') */
 AS HIER_dt_tm
 FROM temp;
</code>```

http://sqlfiddle.com/#!4/6f69b/35

Body:
I am trying to concatenate two fields and load the data into a date field.

I have a table with hier_dt as DATE datatype and hier_tm as CHAR datatype, with data like:

hier_dt   | hier_tm
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
17-JAN-17 | 17:54

I would like to concatenate both of these into a single DATE datatype field, to produce:

hier_dt_tm
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54

Is there a way I can accomplish this?

My current query is:

select to_date(concat(to_char(NVL(hier_DT,'01-JAN-1900'), 'yyyy/mm/dd'),
  concat(' ',NVL(hier_tm,'00:00'))), 'yyyy/mm/dd hh24:mi') as temp
from XXX1

Body:
Try:

 SELECT
 /* TO_DATE( */
  TO_CHAR(hier_dt, 'YYYY/MM/DD') ||
  ' ' ||
  hier_tm
 /* ,'YYYY/MM/DD HH24:MI') */
 AS HIER_dt_tm
 FROM temp;

http://sqlfiddle.com/#!4/6f69b/35


问:
Symfony 4 AuthenticationUtils
I am trying to create a user login with symfony 4 based on the tutorial from symfony.com.

I used the basic services.yaml file with the code below.

https://symfony.com/doc/current/security/form_login_setup.html

```<code>public function loginAction(Request $request, \Twig_Environment $twigRenderer,AuthenticationUtils $authUtils)
{

    // get the login error if there is one
    $error = $authUtils->getLastAuthenticationError();

    // last username entered by the user
    $lastUsername = $authUtils->getLastUsername();

    return new response($twigRenderer->render('security/login.html.twig', array(
        'last_username' => $lastUsername,
        'error'         => $error,
        )
    ));
}
</code>```

Errror:

Controller "App\Controller\SecurityController::loginAction()" requires that you provide a value for the "$authUtils" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

I don`t know how to solve this. Does someone have a suggestion?

答:
I was with the same problem .. Try to run the command:</p>

```<code>composer require security
</code>```

Title: Symfony 4 AuthenticationUtils

Body:
I am trying to create a user login with symfony 4 based on the tutorial from symfony.com.

I used the basic services.yaml file with the code below.

https://symfony.com/doc/current/security/form_login_setup.html

public function loginAction(Request $request, \Twig_Environment $twigRenderer,AuthenticationUtils $authUtils)
{

    // get the login error if there is one
    $error = $authUtils->getLastAuthenticationError();

    // last username entered by the user
    $lastUsername = $authUtils->getLastUsername();

    return new response($twigRenderer->render('security/login.html.twig', array(
        'last_username' => $lastUsername,
        'error'         => $error,
        )
    ));
}

Errror:

Controller "App\Controller\SecurityController::loginAction()" requires that you provide a value for the "$authUtils" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

I don`t know how to solve this. Does someone have a suggestion?

Body:
I was with the same problem .. Try to run the command:

composer require security


问:
JQuery Autocomplete: make ajax call to collect more details of the selected item from autocomplete
What I am trying to do is once a user selects a result from the autocomplete, an ajax call is made to a php file to collect more details about the selected item and then the details coming within response are displayed in a textarea box.

```<code>$(document).ready(function() {
    $("#bookSearch").autocomplete({
        source: "getBooks.php",
        minLength: 3,
        select: function() {
            $.ajax({
                method: "get",
                url: "getBooks2.php"
            })
            .done(function(event, ui){
                $('#bookResults').val(ui.item.value + "\n");
            })
        }
    });
});
</code>```

This is my javascript at the moment. I get an error

"Cannot read property 'value' of undefined" in reference to "$('#bookResults').val(ui.item.value + "\n");".

How can I implement the ajax call into the autocomplete function?

```<code><div id="autoComplete">
    <h2 id="searchTitle">Book search</h2>
    <input type="text" id="bookSearch" placeholder="Type in a book name"/>
    <br>
    <textarea rows="10" cols="40" id="bookResults" readonly></textarea>
</div>
</code>```

答:
Acccording to the documentation, callback function (done()) has only one parameter - data. According to this,

```<code>.done(function(event, ui) {
</code>```

should be replaced with

```<code>.done(function(ui) {
</code>```

Body:
What I am trying to do is once a user selects a result from the autocomplete, an ajax call is made to a php file to collect more details about the selected item and then the details coming within response are displayed in a textarea box.

$(document).ready(function() {
    $("#bookSearch").autocomplete({
        source: "getBooks.php",
        minLength: 3,
        select: function() {
            $.ajax({
                method: "get",
                url: "getBooks2.php"
            })
            .done(function(event, ui){
                $('#bookResults').val(ui.item.value + "\n");
            })
        }
    });
});

This is my javascript at the moment. I get an error

"Cannot read property 'value' of undefined" in reference to "$('#bookResults').val(ui.item.value + "\n");".

How can I implement the ajax call into the autocomplete function?

Book search

    <input type="text" id="bookSearch" placeholder="Type in a book name"/>

    <textarea rows="10" cols="40" id="bookResults" readonly></textarea>

Body:
Acccording to the documentation, callback function (done()) has only one parameter - data. According to this,

.done(function(event, ui) {

should be replaced with

.done(function(ui) {


问:
How to display a specific value from the array in Jquery / getJSON?
Basically I am getting a JSON feed using jquery using:

```<code>$.getJSON("http://localhost/1.php?method=getAllUsers&jsoncallback=?")
</code>```

I get the values successfully from the feed stored in an array called data

eg.:

```<code>x => 1
y => 3
z => 5
</code>```

(obviously this is in the json format)

after this script i have the html, and a table

```<code><table><tr><td>y</td><td>value of y from the feed</td></tr></table>
</code>```

now how can i get the specific value of y into my table? any help would be apreciated.

Thanks

答: Have you tried something that didn't work? Because I would imagine that using json_object.y would give you that value.

Body:
Basically I am getting a JSON feed using jquery using:

$.getJSON("http://localhost/1.php?method=getAllUsers&jsoncallback=?")

I get the values successfully from the feed stored in an array called data

eg.:

x => 1
y => 3
z => 5

(obviously this is in the json format)

after this script i have the html, and a table

y	value of y from the feed

now how can i get the specific value of y into my table? any help would be apreciated.

Thanks


问:
School assignments about arrays and looping through them
I was assigned to make the below application

The computer inserts 20 random numbers (with values between 0 and 200)
  in an array of 20 elements. After the array has been completely
  filled, all elements are shown and the average of the numbers in the
  array is determined and shown. Lastly, the difference between the
  numbers in the array with the average is shown

I managed to make half of the program but now am at the point where I have to make the app shows the difference between each element of the array and the average and I can't manage to think of a formula to get this done !!!

this is my code so far and it Answers half of the question.

```<code>  static void Main(string[] args)
    {
        int sum = 0;
        int[] numbers = new int[20];
        Random numbergenarator = new Random();
        for(int i=0; i<numbers.Length;)
        {
            numbers[i] = numbergenarator.Next(0, 201);
            Console.WriteLine("Element "+i +" is: "+ numbers[i]);
            sum += numbers[i];
            i++;
        }
        int average = sum / 20;
        Console.WriteLine("The average is: " + average);
        Console.ReadKey();
    }
</code>```

thanks in Advance

答:
the resolution to my issues was by adding another (for loop) for generating the difference between each element and the average of elements.
for better comprehension read the code down through :D</p>

```<code>static void Main(string[] args)
{
    int sum = 0;
    int[] numbers = new int[20];
    Random numbergenarator = new Random();

    for(int i = 0; i<numbers.Length;)
    {
        numbers[i] = numbergenarator.Next(0, 201);
        Console.WriteLine("Element "+i +" is: "+ numbers[i]);
        sum += numbers[i];
        i++;
    }

    int average = sum / 20;
    Console.WriteLine("The average is: " + average);

    for (int i = 0; i < numbers.Length;)
    {
        Console.WriteLine("the difference between the average and the element " + i +
            " is " + (average - numbers[i]));
        i++;
    }

    Console.ReadKey();
}
</code>```

Body:
I was assigned to make the below application

The computer inserts 20 random numbers (with values between 0 and 200)
  in an array of 20 elements. After the array has been completely
  filled, all elements are shown and the average of the numbers in the
  array is determined and shown. Lastly, the difference between the
  numbers in the array with the average is shown

I managed to make half of the program but now am at the point where I have to make the app shows the difference between each element of the array and the average and I can't manage to think of a formula to get this done !!!

this is my code so far and it Answers half of the question.

  static void Main(string[] args)
    {
        int sum = 0;
        int[] numbers = new int[20];
        Random numbergenarator = new Random();
        for(int i=0; i<numbers.Length;)
        {
            numbers[i] = numbergenarator.Next(0, 201);
            Console.WriteLine("Element "+i +" is: "+ numbers[i]);
            sum += numbers[i];
            i++;
        }
        int average = sum / 20;
        Console.WriteLine("The average is: " + average);
        Console.ReadKey();
    }

thanks in Advance

Body:
the resolution to my issues was by adding another (for loop) for generating the difference between each element and the average of elements.
for better comprehension read the code down through :D

static void Main(string[] args)
{
    int sum = 0;
    int[] numbers = new int[20];
    Random numbergenarator = new Random();

    for(int i = 0; i<numbers.Length;)
    {
        numbers[i] = numbergenarator.Next(0, 201);
        Console.WriteLine("Element "+i +" is: "+ numbers[i]);
        sum += numbers[i];
        i++;
    }

    int average = sum / 20;
    Console.WriteLine("The average is: " + average);

    for (int i = 0; i < numbers.Length;)
    {
        Console.WriteLine("the difference between the average and the element " + i +
            " is " + (average - numbers[i]));
        i++;
    }

    Console.ReadKey();
}


问:
Using same generic wildcard in 2 objects
I am trying to copy the CellFactory from one TableColumn to another. The issue I'm running into is with generics.

The problem being that table.getColumns() returns a list of TableColumn<X, ?> and I want to create a new column, with the same Tablecolumn<X, ?> parameters but there is no way for me to know the second, ? parameter.

```<code>for (TableColumn<X, ?> col : table.getColumns()) {
    TableColumn<X, ?> newCol = new TableColumn<>();
    newCol.setCellValueFactory(col.getCellValueFactory()); // Error <X, ?> != <X, ?>
}
</code>```

Am I able to define a generic type that will be used in both instances? Or is this not possible due to the generic information being lost at runtime?

Edit:

Casting it to a TableColumn<X, Object> seems to work but this feels very wrong and I would rather not rely on casting to an Object.

```<code>for (TableColumn<X, ?> col : table.getColumns()) {
    TableColumn<X, Object> tempCol = (TableColumn<X, Object>) col;
    TableColumn<X, Object> newCol = new TableColumn<>();
    newCol.setCellValueFactory(tempCol.getCellValueFactory());
}
</code>```

答:
In Java wildcard stands as an unknown type. This means that two unknown types cannot be of same type. In order to tell the compiler that we are dealing with the same unknown type we need to define a temporary generic type Y that will bound two TableColumns to the same type. The only way we can do this is to move the creation and updating of new TableColumn into a separate parametrized method like this:

```<code>for ( TableColumn<X, ?> col : getColumns() ) {
        TableColumn<X, ?> newCol = create(col);
}

public <Y> TableColumn<X, ?> create(TableColumn<X, Y> tc){
    TableColumn<X, Y> newCol = new TableColumn<>();
    newCol.setCellValueFactory( tc.getCellValueFactory() );
    return newCol;
}
</code>```

Body:
I am trying to copy the CellFactory from one TableColumn to another. The issue I'm running into is with generics.

The problem being that table.getColumns() returns a list of TableColumn<X, ?> and I want to create a new column, with the same Tablecolumn<X, ?> parameters but there is no way for me to know the second, ? parameter.

for (TableColumn<X, ?> col : table.getColumns()) {
    TableColumn<X, ?> newCol = new TableColumn<>();
    newCol.setCellValueFactory(col.getCellValueFactory()); // Error <X, ?> != <X, ?>
}

Am I able to define a generic type that will be used in both instances? Or is this not possible due to the generic information being lost at runtime?

Edit:

Casting it to a TableColumn<X, Object> seems to work but this feels very wrong and I would rather not rely on casting to an Object.

for (TableColumn<X, ?> col : table.getColumns()) {
    TableColumn<X, Object> tempCol = (TableColumn<X, Object>) col;
    TableColumn<X, Object> newCol = new TableColumn<>();
    newCol.setCellValueFactory(tempCol.getCellValueFactory());
}

Body:
In Java wildcard stands as an unknown type. This means that two unknown types cannot be of same type. In order to tell the compiler that we are dealing with the same unknown type we need to define a temporary generic type Y that will bound two TableColumns to the same type. The only way we can do this is to move the creation and updating of new TableColumn into a separate parametrized method like this:

for ( TableColumn<X, ?> col : getColumns() ) {
        TableColumn<X, ?> newCol = create(col);
}

public <Y> TableColumn<X, ?> create(TableColumn<X, Y> tc){
    TableColumn<X, Y> newCol = new TableColumn<>();
    newCol.setCellValueFactory( tc.getCellValueFactory() );
    return newCol;
}


问:
Frequency count for Comma delimited categories within a column
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

```<code>Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda
</code>```

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

答:
Thank you all for sharing the answers. I was actually able to solve it also just on my end by using sqldf package. BB2 is the original data-set that contain zip and Concatenated make columns. Here is the code

D1 <- strsplit(BB2$MakeConcat, split = ",")

  View(BB2)

  D2<- data.frame(zip= rep(BB2$zip, sapply(D1, length)),MakeConcat=unlist(D1))

  View(D2)

  D3<- sqldf("select zip, count(MakeConcat) as count2, MakeConcat from D2 group by zip, MakeConcat order by zip desc")

   View(D3)

  D4 <- mydf[order(D3$count2, D3$zip, decreasing = TRUE),]

  D4 <- D3[order(D3$count2, D3$zip, decreasing = TRUE),]

  D4_x<- D4[ave(D4$count, D4$zip, FUN = seq_along) <= 3,]

  View(D4_x)

  Final<- sqldf("SELECT zip, upper(GROUP_CONCAT(MakeConcat)) as MakeConcat FROM D4_x group by zip")

Body:
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?