问:
How to ensure requests to my servers functions only by a single origin / UI?
I have a node.js server that has HTTP CRUD functions to my mongoDB.

And an Android application that sends requests though those functions.

I would like to ensure that my server will answer requests from specific origins.

For example: only answer requests from the android app, or my pc postman's requests.

How can I ensure that no one else sending requests using the same urls and ports will get answered?

This is my server.js file:

```<code>const express = require('express');
const MongoClient = require('mongodb');
const bodyParser = require('body-parser');
var db = require('./config/db');
var app = express();

const port = 8000;
app.use(bodyParser.json());

MongoClient.connect(db.url, (err, database) => {
    if (err) return console.log(err)

    db = database.db("getremp")
    require('./app/routes')(app, db);

        app.listen(process.env.PORT || port, () => {

            console.log("Express server listening on port %d in %s mode - We Are lIVE!",app.settings.env.port, app.settings.env);
    });

})
</code>```

and my index.js:

```<code>const noteRoutes = require('./note_routes');
module.exports = function (app, db) {
    noteRoutes(app, db);
};
</code>```

答:
You can control this with :

Send a specific header with your datas containing a secret key, then control the header in your node app How to check headers in nodejs?

Use HMAC in order to authenticate the user and control the integrity of datas : Node Hmac Authentication

But you've to remember that all traffic going out from an mobile app can be intercept (with Fiddler for example). Never use a static (non-dynamic) value to ensure authentication

Body:
I have a node.js server that has HTTP CRUD functions to my mongoDB.

And an Android application that sends requests though those functions.

I would like to ensure that my server will answer requests from specific origins.

For example: only answer requests from the android app, or my pc postman's requests.

How can I ensure that no one else sending requests using the same urls and ports will get answered?

This is my server.js file:

const express = require('express');
const MongoClient = require('mongodb');
const bodyParser = require('body-parser');
var db = require('./config/db');
var app = express();

const port = 8000;
app.use(bodyParser.json());

MongoClient.connect(db.url, (err, database) => {
    if (err) return console.log(err)

    db = database.db("getremp")
    require('./app/routes')(app, db);

        app.listen(process.env.PORT || port, () => {

            console.log("Express server listening on port %d in %s mode - We Are lIVE!",app.settings.env.port, app.settings.env);
    });

})

and my index.js:

const noteRoutes = require('./note_routes');
module.exports = function (app, db) {
    noteRoutes(app, db);
};


来源: stackexchange

问:
Is there an implicit default constructor in C++?
In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?</p>

答:
The compiler will generate default constructors and destructors if user-created ones are not present. These will NOT modify the state of any data members.

In C++ (and C) the contents of any allocated data is not guaranteed. In debug configurations some platforms will set this to a known value (e.g. 0xFEFEFEFE) to help identify bugs, but this should not be relied upon.

OwnerDisplayName: Skilldrick

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Andrew Grant


问:
how to Style gridview rows during runtime in wpf?
```<code><ListView.View>
            <GridView>
                <GridViewColumn Header="اسم الشركة" DisplayMemberBinding="{Binding Path=company_name}" Width="200" />
                <GridViewColumn Header="رمز الشركة" DisplayMemberBinding="{Binding Path=symbol}" Width="Auto" />
                <GridViewColumn Header="سعر السهم"  DisplayMemberBinding="{Binding Path=price}" Width="Auto" />
                <GridViewColumn Header="نسبة التغير" DisplayMemberBinding="{Binding Path=change_percent}" Width="Auto" />
            </GridView>
        </ListView.View>
</code>```

I have the previous XAML tags to define the listview I am using in my wpf - C# application
I want to give each row in my listview a specific color that would be chosen during runtime

I know it might be a silly question but I need it badly and I have looked for it alot with no results

Can you help me ?

答: Is this something you are looking for?</p>

ContentLicense: CC BY-SA 3.0

Body:
<ListView.View>
            <GridView>
                <GridViewColumn Header="اسم الشركة" DisplayMemberBinding="{Binding Path=company_name}" Width="200" />
                <GridViewColumn Header="رمز الشركة" DisplayMemberBinding="{Binding Path=symbol}" Width="Auto" />
                <GridViewColumn Header="سعر السهم"  DisplayMemberBinding="{Binding Path=price}" Width="Auto" />
                <GridViewColumn Header="نسبة التغير" DisplayMemberBinding="{Binding Path=change_percent}" Width="Auto" />
            </GridView>
        </ListView.View>

I have the previous XAML tags to define the listview I am using in my wpf - C# application
I want to give each row in my listview a specific color that would be chosen during runtime

I know it might be a silly question but I need it badly and I have looked for it alot with no results

Can you help me ?

Body: Is this something you are looking for?


问:
how to set data to firebase map object
I have a firebase map object and i need to insert arrays inside

I am trying to use update function but it doesn't work

```<code>dialogRef.afterClosed().subscribe(result => {
  console.log(result);

  const arrayname = result.name;
  const fireupdate = this.af.list('/users/' + this.Uid + '/items').update(arrayname, result);
});
</code>```

this is how the result array looks like

```<code>{name: "item", price: 25, desc: "a simple item"}
</code>```

I don't get anything in the firebase

答:
If I am not mistaking, by doing this.af.list('/users/' + this.Uid + '/items').update() you are actually trying to write to the Realtime Database, see https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md#updating-items-in-the-list-using-update

But the database that you show in your question is Firestore, the other database service offered by Firebase.

You should use the part of the angularfire2 library dedicated to Firestore, see https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md#using-angularfirestoredocument

ContentLicense: CC BY-SA 4.0

Title: how to set data to firebase map object

Body:
I have a firebase map object and i need to insert arrays inside

I am trying to use update function but it doesn't work

dialogRef.afterClosed().subscribe(result => {
  console.log(result);

  const arrayname = result.name;
  const fireupdate = this.af.list('/users/' + this.Uid + '/items').update(arrayname, result);
});

this is how the result array looks like

{name: "item", price: 25, desc: "a simple item"}

I don't get anything in the firebase


问:
if Column A cell matches Column B cell, display column C value of same row as column B
if Column A cell matches Column B cell, display column C value of same row as column B

ColumnA in first excel file

```<code>liu.weio@xy.com
tonny@ab.com
wong@ab.com
might@ab.com
daniel@ab.com.br
user@ab.com.br
random@ab.com
Any@ab.com
</code>```

ColumnB, ColumnC in second excel file

```<code>liu.weio@xy.com, US
tonny@ab.com, FR
wong@ab.com, IN
might@ab.com, JP
daniel@ab.com.br, CH
user@ab.com.br, AU
random@ab.com, RU
Any@ab.com, DE
extra@ab.com, PL
EXTRA1@av.com, RU
</code>```

Expected result in first excel as Column A and Column B

```<code>liu.weio@xy.com, US
tonny@ab.com, FR
wong@ab.com, IN
might@ab.com, JP
daniel@ab.com.br, CH
user@ab.com.br, AU
random@ab.com, RU
Any@ab.com, DE
</code>```

I tried with vlookup but not working with 3 columns

Body:
if Column A cell matches Column B cell, display column C value of same row as column B

ColumnA in first excel file

liu.weio@xy.com
tonny@ab.com
wong@ab.com
might@ab.com
daniel@ab.com.br
user@ab.com.br
random@ab.com
Any@ab.com

ColumnB, ColumnC in second excel file

liu.weio@xy.com, US
tonny@ab.com, FR
wong@ab.com, IN
might@ab.com, JP
daniel@ab.com.br, CH
user@ab.com.br, AU
random@ab.com, RU
Any@ab.com, DE
extra@ab.com, PL
EXTRA1@av.com, RU

Expected result in first excel as Column A and Column B

liu.weio@xy.com, US
tonny@ab.com, FR
wong@ab.com, IN
might@ab.com, JP
daniel@ab.com.br, CH
user@ab.com.br, AU
random@ab.com, RU
Any@ab.com, DE

I tried with vlookup but not working with 3 columns

Body:
Try:

=IF(A1<>"",IF(A1=LEFT(B1,LEN(A1)),B1,""),"")


问:
Get routes that use certain middleware or are in certain group?
Is it possible in Laravel in Controller, to get all routes that are in one group, or routes that use certain middleware or something else?
Here is an example of what I mean:

```<code>Route::middleware(['auth', 'admin])->group(function () {
    Route::patch('/updateClient', 'ClientController@update');
    Route::resource('server-groups','ServerGroupsController');
});
</code>```

And in my controller to have something like this, that will get me all routes where middleware is admin:

```<code>$routes = Route::where('middleware', 'admin');
</code>```

Currently I can only get all routes with this code:

```<code>$routes = Route::getRoutes();
</code>```

答:
You can use laravel's built-in gatherMiddleware() method that will return all middlewares attached to a route in an array, by default it will include the web route but you can remove it if you want, also, use the route method from the request helper.

```<code>$routes = request()->route()->gatherMiddleware();

dd($routes); // will display : array(0 => 'web', 1 => 'auth', 2 => 'admin');

dd(array_slice($routes, 1, null, true)) // will display : array(1 => 'auth', 2 => 'admin');
</code>```

Body:
Is it possible in Laravel in Controller, to get all routes that are in one group, or routes that use certain middleware or something else?
Here is an example of what I mean:

Route::middleware(['auth', 'admin])->group(function () {
    Route::patch('/updateClient', 'ClientController@update');
    Route::resource('server-groups','ServerGroupsController');
});

And in my controller to have something like this, that will get me all routes where middleware is admin:

$routes = Route::where('middleware', 'admin');

Currently I can only get all routes with this code:

$routes = Route::getRoutes();

Body:
You can use laravel's built-in gatherMiddleware() method that will return all middlewares attached to a route in an array, by default it will include the web route but you can remove it if you want, also, use the route method from the request helper.

$routes = request()->route()->gatherMiddleware();

dd($routes); // will display : array(0 => 'web', 1 => 'auth', 2 => 'admin');

dd(array_slice($routes, 1, null, true)) // will display : array(1 => 'auth', 2 => 'admin');


问:
Kill process after a given time bash?
I have a script that tries to make a DB connection using another program and the timeout(2.5min) of the program is to long. I want to add this functionality to the script.

If it takes longer then 5 seconds to connect, kill the process

Else kill the sleep/kill process.

The issue I'm having is how bash reports when a process is killed, that's because the processes are in the same shell just the background. Is there a better way to do this or how can I silence the shell for the kill commands?

```<code>DB_CONNECTION_PROGRAM > $CONNECTFILE &
pid=$!
(sleep 5; kill $pid) &
sleep_pid=$!
wait $pid

# If the DB failed to connect after 5 seconds and was killed
status=$? #Kill returns 128+n (fatal error)
if [ $status -gt 128 ]; then
    no_connection="ERROR: Timeout while trying to connect to $dbserver"
else # If it connected kill the sleep and any errors collect
    kill $sleep_pid
    no_connection=`sed -n '/^ERROR:/,$p' $CONNECTFILE`
fi
</code>```

答:
You can set a timeout after 2 hours and restart your javaScriptThatStalls 100 times this way in a loop

```<code>seq 100|xargs -II timeout $((2 * 60 * 60)) javaScriptThatStalls
</code>```

Title: Kill process after a given time bash?

Body:
I have a script that tries to make a DB connection using another program and the timeout(2.5min) of the program is to long. I want to add this functionality to the script.

If it takes longer then 5 seconds to connect, kill the process

Else kill the sleep/kill process.

The issue I'm having is how bash reports when a process is killed, that's because the processes are in the same shell just the background. Is there a better way to do this or how can I silence the shell for the kill commands?

DB_CONNECTION_PROGRAM > $CONNECTFILE &
pid=$!
(sleep 5; kill $pid) &
sleep_pid=$!
wait $pid

# If the DB failed to connect after 5 seconds and was killed
status=$? #Kill returns 128+n (fatal error)
if [ $status -gt 128 ]; then
    no_connection="ERROR: Timeout while trying to connect to $dbserver"
else # If it connected kill the sleep and any errors collect
    kill $sleep_pid
    no_connection=`sed -n '/^ERROR:/,$p' $CONNECTFILE`
fi

Body:
You can set a timeout after 2 hours and restart your javaScriptThatStalls 100 times this way in a loop

seq 100|xargs -II timeout $((2 * 60 * 60)) javaScriptThatStalls


问:
How could I check if progress bar is full and then open an .bat file?
I don't know exactly where the code should be put and what code should look like. I need help, because I am very new to c#

```<code>    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            this.timer1.Start();
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            this.progressBar1.Increment(1);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
           this.TopMost = true;
        }

        private void ProgressBar1_Click(object sender, EventArgs e)
        {

        }
    }
}
</code>```

When I try the method from old videos, there is no such a thing as it and it shows that progressBar1 doesn't exist.

答:
Just compare the progressBar1.Value

```<code>// progressBar1.Value = 0;
// progressBar1.Minimum = 0;
// progressBar1.Maximum = 100;

private void Timer1_Tick(object sender, EventArgs e)
{
    this.progressBar1.Increment(1);
    if(progressBar1.Value == progressBar1.Maximum){
        Process.Start("c:\\file.bat");
    }
}
</code>```

Body:
I don't know exactly where the code should be put and what code should look like. I need help, because I am very new to c#

    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            this.timer1.Start();
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            this.progressBar1.Increment(1);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
           this.TopMost = true;
        }

        private void ProgressBar1_Click(object sender, EventArgs e)
        {

        }
    }
}

When I try the method from old videos, there is no such a thing as it and it shows that progressBar1 doesn't exist.

Body:
Just compare the progressBar1.Value

// progressBar1.Value = 0;
// progressBar1.Minimum = 0;
// progressBar1.Maximum = 100;

private void Timer1_Tick(object sender, EventArgs e)
{
    this.progressBar1.Increment(1);
    if(progressBar1.Value == progressBar1.Maximum){
        Process.Start("c:\\file.bat");
    }
}


问:
How to calculate mean of columns from array lists in python using numpy?
I am trying to calculate the mean average of columns from a list of arrays.

```<code>f1_score = [array([0.807892  , 0.91698113, 0.73846154]),
            array([0.80041797, 0.9056244 , 0.72017837]),
            array([0.80541103, 0.91493384, 0.70282486])]
</code>```

I also tried as mentioned below, but I couldn't get the mean value for columns.

```<code>output = []
for i in range(len(f1_score)):
   output.append(np.mean(f1_score[i], axis = 0))
</code>```

I get the mean values for rows:

```<code>[0.8211115582302323, 0.8087402497928408, 0.8077232421210242]
</code>```

But I need the mean values for columns:

```<code>array([0.8045736667, 0.9125131233, 0.7204882567])
</code>```

Thanks in advance for your answer.

答:
You can use numpy's mean function and set the axis as 0.

```<code>mean(f1_score, axis=0)
</code>```

And then you get the required answer

```<code>array([0.80457367, 0.91251312, 0.72048826])
</code>```

Body:
I am trying to calculate the mean average of columns from a list of arrays.

f1_score = [array([0.807892  , 0.91698113, 0.73846154]),
            array([0.80041797, 0.9056244 , 0.72017837]),
            array([0.80541103, 0.91493384, 0.70282486])]

I also tried as mentioned below, but I couldn't get the mean value for columns.

output = []
for i in range(len(f1_score)):
   output.append(np.mean(f1_score[i], axis = 0))

I get the mean values for rows:

[0.8211115582302323, 0.8087402497928408, 0.8077232421210242]

But I need the mean values for columns:

array([0.8045736667, 0.9125131233, 0.7204882567])

Thanks in advance for your answer.

Body:
You can use numpy's mean function and set the axis as 0.

mean(f1_score, axis=0)

And then you get the required answer

array([0.80457367, 0.91251312, 0.72048826])


问:
How can I separate variable and set the key to true for swift?
I want to separate the string in var into different vars and set key to true. For example

var x = [English , Chinese , Maths] => "English":true "Chinese":true
  "Maths":true

and push to firebase in order to get a data structure like:

name:anon subject:{"English":true
           "Chinese":true
           "Maths":true}

What should I do ?

答:
You can first remove duplicates from your array (or not do this if you are sure), map each item of the array to tuple with true as the second item, then use Dictionary.init(uniqueKeysWithValues:):

```<code>let result = Dictionary(uniqueKeysWithValues: Set(a).map { ($0, true) })
</code>```

Body:
You can first remove duplicates from your array (or not do this if you are sure), map each item of the array to tuple with true as the second item, then use Dictionary.init(uniqueKeysWithValues:):

let result = Dictionary(uniqueKeysWithValues: Set(a).map { ($0, true) })


问:
How fix not working ActionResult Update in NET Core?
I'm learning about .NET Core and I'm using code from this tutorial. But my update sql is not working.

Here is the index view code:

```<code>        public ActionResult Index(int? id)
    {
        ViewBag.Operation = id;
        ViewBag.Name = db.Chars.ToList();
        Chars Chars = db.Chars.Find(id);
        return View(Chars);
    }
</code>```

As for now it work I see results from sql and here is the updated part:

```<code>        public ActionResult Update(Chars Chars)
    {
        if (ModelState.IsValid)
        {
            db.Entry(Chars).State = EntityState.Modified;
            db.SaveChanges();
        }
        return RedirectToAction("Index", new { id = 0 });
    }
</code>```

Here is index.cshtml part:

```<code>   @using (Html.BeginForm()
{
    @foreach (var item in (IEnumerable<MVC__test_2.Chars>)ViewBag.Name)
    {
        <div class="form-group">
            <div class="col-md-10">
                @Html.EditorFor(modelItem => item.CharName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.HiddenFor(modelItem => item.CharID, new { id = item.CharID })
            </div>
        </div>
        @Html.ActionLink("Index", "Index", new { id = item.CharID })
<input type="submit" value="Update" name="Update"
       style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0)   ? "display:block" : "display:none") />
    }
}
</code>```

答:
According to the tutorial you provided , I made a demo to test and it updated the data well. The following is the working example , you could refer to and make the modification as per your need .

Model

```<code>public class Description
{
    public int Id { get; set; }
    public string Display { get; set; }
}
</code>```

Controller

```<code>public IActionResult Index(int? id)
    {
        ViewBag.Operation = id;
        ViewBag.Name = _context.Description.ToList();
        Description description= _context.Description.Find(id);
        return View(description);
    }

public ActionResult Update(Description description)
    {
        if (ModelState.IsValid)
        {
            _context.Entry(description).State = EntityState.Modified;
            _context.SaveChanges();
        }
        return RedirectToAction("Index", new { id = 0 });
    }
</code>```

Index.cshtml , you should hide the id of the modified data in the modification section.

```<code>@model WebApplication1.Models.Description

@using (Html.BeginForm("Update", "Home", FormMethod.Post))
{
    @foreach (var item in (IEnumerable<WebApplication1.Models.Description >)ViewBag.Name)
    {
        <div class="form-group">
           <div class="col-md-10">
               @Html.EditorFor(modelItem => item.Display, new { htmlAttributes = new { @class = "form-control" } })
               @Html.HiddenFor(modelItem => item.Id, new { id = item.Id })
           </div>
       </div>
       @Html.ActionLink("Edit", "Index", new { id = item.Id })
   }

   // Create or Update data
   @Html.AntiForgeryToken()
   <div class="form-horizontal">
       @Html.ValidationSummary(true)
       <fieldset>
          <legend> <b>Entry Screen</b></legend>
          <div class="form-group">
             @Html.LabelFor(model => model.Display, new { @class = "control-label col-md-2" })
             @Html.HiddenFor(model => model.Id)
             <div class="col-md-10">
                @Html.EditorFor(model => model.Display)
                @Html.ValidationMessageFor(model => model.Display)
             </div>
          </div>

          <div class="form-group">
              <p>
                  <input type="submit" value="Create" name="Create"
                       style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:none" : "display:block") />
                  <input type="submit" value="Update" name="Update"
                       style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
              </p>
          </div>
       </fieldset>
   </div>
}
</code>```

Body:
I'm learning about .NET Core and I'm using code from this tutorial. But my update sql is not working.

Here is the index view code:

        public ActionResult Index(int? id)
    {
        ViewBag.Operation = id;
        ViewBag.Name = db.Chars.ToList();
        Chars Chars = db.Chars.Find(id);
        return View(Chars);
    }

As for now it work I see results from sql and here is the updated part:

        public ActionResult Update(Chars Chars)
    {
        if (ModelState.IsValid)
        {
            db.Entry(Chars).State = EntityState.Modified;
            db.SaveChanges();
        }
        return RedirectToAction("Index", new { id = 0 });
    }

Here is index.cshtml part:

   @using (Html.BeginForm()
{
    @foreach (var item in (IEnumerable<MVC__test_2.Chars>)ViewBag.Name)
    {

                @Html.EditorFor(modelItem => item.CharName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.HiddenFor(modelItem => item.CharID, new { id = item.CharID })

        @Html.ActionLink("Index", "Index", new { id = item.CharID })
<input type="submit" value="Update" name="Update"
       style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0)   ? "display:block" : "display:none") />
    }
}

Body:
According to the tutorial you provided , I made a demo to test and it updated the data well. The following is the working example , you could refer to and make the modification as per your need .

Model

public class Description
{
    public int Id { get; set; }
    public string Display { get; set; }
}

Controller

public IActionResult Index(int? id)
    {
        ViewBag.Operation = id;
        ViewBag.Name = _context.Description.ToList();
        Description description= _context.Description.Find(id);
        return View(description);
    }

public ActionResult Update(Description description)
    {
        if (ModelState.IsValid)
        {
            _context.Entry(description).State = EntityState.Modified;
            _context.SaveChanges();
        }
        return RedirectToAction("Index", new { id = 0 });
    }

Index.cshtml , you should hide the id of the modified data in the modification section.

@model WebApplication1.Models.Description

@using (Html.BeginForm("Update", "Home", FormMethod.Post))
{
    @foreach (var item in (IEnumerable<WebApplication1.Models.Description >)ViewBag.Name)
    {
        <div class="form-group">
           <div class="col-md-10">
               @Html.EditorFor(modelItem => item.Display, new { htmlAttributes = new { @class = "form-control" } })
               @Html.HiddenFor(modelItem => item.Id, new { id = item.Id })
           </div>
       </div>
       @Html.ActionLink("Edit", "Index", new { id = item.Id })
   }

   // Create or Update data
   @Html.AntiForgeryToken()
   <div class="form-horizontal">
       @Html.ValidationSummary(true)
       <fieldset>
          <legend> <b>Entry Screen</b></legend>
          <div class="form-group">
             @Html.LabelFor(model => model.Display, new { @class = "control-label col-md-2" })
             @Html.HiddenFor(model => model.Id)
             <div class="col-md-10">
                @Html.EditorFor(model => model.Display)
                @Html.ValidationMessageFor(model => model.Display)
             </div>
          </div>

          <div class="form-group">
              <p>
                  <input type="submit" value="Create" name="Create"
                       style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:none" : "display:block") />
                  <input type="submit" value="Update" name="Update"
                       style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
              </p>
          </div>
       </fieldset>
   </div>
}


问:
How to group text being typed into an array and wrap every 20 chars in a div
I am attempting to wrap every 20 chars in a new div container.  I keep getting undefined I assume from the array results that do not exist yet.  How can I wrap every 20 chars as the user types and reaches char 20, 40, 60,and 80 and place it into a div container with the max allowed chars being 80, and is there a better way of doing this than writing out the array groups manually by 20's.

function creaeTextField(clicked_id) {
  var dropArea = document.getElementById('headarea');
  var myArea = document.createElement('div');
  var myAreaOuter = document.createElement('div');

  myArea.className = "areaClass";
  myAreaOuter.className = "areaClassOuter";

  myArea.id = "areaClass";
  myAreaOuter.id = "areaClassOuter";

  myArea.contentEditable = "true";

  if (clicked_id == 'text') {
    myAreaOuter.appendChild(myArea);
    dropArea.appendChild(myAreaOuter);

    myArea.addEventListener("keydown", findLimitb);
    myArea.addEventListener("keyup", findLimitb);

    var style = window.getComputedStyle(myArea, null).getPropertyValue('font-size');
    var fontSize = parseFloat(style);

    function findLimitb() {
      if (myArea.offsetHeight <= fontSize * 4) {
        myArea.addEventListener("keydown", breaker);
      } else {
        if (event.keyCode === 8 || event.keyCode === 46 || event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) {
          myArea.focus();
        } else {
          myArea.removeEventListener("keydown", breaker);
          event.preventDefault();
          myArea.style.height = fontSize * 4 + "px";
        }
      }
    }

    function breaker() {
      var myAr = myArea.innerHTML.split("");
      var divCon = document.createElement('div');
      myArea.appendChild(divCon);
      if (myArea.innerHTML.length > 20) {
        divCon.innerHTML = myAr[0] + myAr[1] + myAr[2] + myAr[3] + myAr[4] + myAr[5] + myAr[6] + myAr[7] + myAr[8] + myAr[9] + myAr[10] + myAr[11] + myAr[12] + myAr[13] + myAr[14] + myAr[15] + myAr[16] + myAr[17] + myAr[18] + myAr[19] + myAr[20];
      }
    }

  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.headarea {
  width: 100%;
  height: 130px;
  float: left;
}

.buttonStyle {
  width: 60px;
  height: 25px;
  float: left;
}

.areaClassOuter {
  float: left;
  padding: 10px;
  position: relative;
  z-index: 29;
  border: 1px #000000 solid;
}

.areaClass {
  min-width: 100px;
  max-width: 310px;
  min-height: 60px;
  max-height: 100px;
  float: left;
  padding: 7px;
  position: relative;
  z-index: 30;
  border: 1px #000000 solid;
  overflow: hidden;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 24pt;
  text-align: center;
}</code>```

<button class="buttonStyle" id="text" type="button" onclick="creaeTextField(this.id)"></button>```

答:
You could split the string into spaces and use a modulus to see when 20 items have been reached.

This makes the code independent and allows you to change the number of words allowed in each string.

We split on the space and then iterate over the words, we reconstruct the string but push the results into an array when we reach the 'paragraphlength'. You then end up with an array of strings that are 20 words long.

There are some edge cases that aren't covered here and may not be an issue depending on your use case. For example, what if a user just puts illegible characters in, ect

//The wording as a string
const words = "this is a really long set of words that need to be broken down into a paragraphs array that has lots of words that need to be broken down into a nicer structure for users to easier consume. We split on the space and then iterate over the words, we reconstruct the string but push the results into an array when we reach the 'paragraphlength'";

const getParagraphs = (words, paragraphLength) => {
  let paragraphs =[];
  words.split(" ").reduce((memo, word, index) => {
    if(index > 0 && index % paragraphLength === 0)
    {
        paragraphs.push(memo);
        memo = "";
    }
    return memo + " " + word;
  }, "");
  return paragraphs
}

const paragraphs = getParagraphs(words, 20);
console.log("original string ===>", words);
console.log("paragraphs array ===>", paragraphs);
//below is for display purposes only
let results = document.getElementById('results');
paragraphs.forEach(paragraph => {
  const para = document.createElement("p");
  const node = document.createTextNode(paragraph);
   para.appendChild(node);
   results.appendChild(para);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="results">
</div></code>```

Body:
I am attempting to wrap every 20 chars in a new div container.  I keep getting undefined I assume from the array results that do not exist yet.  How can I wrap every 20 chars as the user types and reaches char 20, 40, 60,and 80 and place it into a div container with the max allowed chars being 80, and is there a better way of doing this than writing out the array groups manually by 20's.

function creaeTextField(clicked_id) {
  var dropArea = document.getElementById('headarea');
  var myArea = document.createElement('div');
  var myAreaOuter = document.createElement('div');

  myArea.className = "areaClass";
  myAreaOuter.className = "areaClassOuter";

  myArea.id = "areaClass";
  myAreaOuter.id = "areaClassOuter";

  myArea.contentEditable = "true";

  if (clicked_id == 'text') {
    myAreaOuter.appendChild(myArea);
    dropArea.appendChild(myAreaOuter);

    myArea.addEventListener("keydown", findLimitb);
    myArea.addEventListener("keyup", findLimitb);

    var style = window.getComputedStyle(myArea, null).getPropertyValue('font-size');
    var fontSize = parseFloat(style);

    function findLimitb() {
      if (myArea.offsetHeight <= fontSize * 4) {
        myArea.addEventListener("keydown", breaker);
      } else {
        if (event.keyCode === 8 || event.keyCode === 46 || event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) {
          myArea.focus();
        } else {
          myArea.removeEventListener("keydown", breaker);
          event.preventDefault();
          myArea.style.height = fontSize * 4 + "px";
        }
      }
    }

    function breaker() {
      var myAr = myArea.innerHTML.split("");
      var divCon = document.createElement('div');
      myArea.appendChild(divCon);
      if (myArea.innerHTML.length > 20) {
        divCon.innerHTML = myAr[0] + myAr[1] + myAr[2] + myAr[3] + myAr[4] + myAr[5] + myAr[6] + myAr[7] + myAr[8] + myAr[9] + myAr[10] + myAr[11] + myAr[12] + myAr[13] + myAr[14] + myAr[15] + myAr[16] + myAr[17] + myAr[18] + myAr[19] + myAr[20];
      }
    }

  }
}

.headarea {
  width: 100%;
  height: 130px;
  float: left;
}

.buttonStyle {
  width: 60px;
  height: 25px;
  float: left;
}

.areaClassOuter {
  float: left;
  padding: 10px;
  position: relative;
  z-index: 29;
  border: 1px #000000 solid;
}

.areaClass {
  min-width: 100px;
  max-width: 310px;
  min-height: 60px;
  max-height: 100px;
  float: left;
  padding: 7px;
  position: relative;
  z-index: 30;
  border: 1px #000000 solid;
  overflow: hidden;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 24pt;
  text-align: center;
}

<button class="buttonStyle" id="text" type="button" onclick="creaeTextField(this.id)"></button>

Body:
You could split the string into spaces and use a modulus to see when 20 items have been reached.

This makes the code independent and allows you to change the number of words allowed in each string.

We split on the space and then iterate over the words, we reconstruct the string but push the results into an array when we reach the 'paragraphlength'. You then end up with an array of strings that are 20 words long.

There are some edge cases that aren't covered here and may not be an issue depending on your use case. For example, what if a user just puts illegible characters in, ect

//The wording as a string
const words = "this is a really long set of words that need to be broken down into a paragraphs array that has lots of words that need to be broken down into a nicer structure for users to easier consume. We split on the space and then iterate over the words, we reconstruct the string but push the results into an array when we reach the 'paragraphlength'";

const getParagraphs = (words, paragraphLength) => {
  let paragraphs =[];
  words.split(" ").reduce((memo, word, index) => {
    if(index > 0 && index % paragraphLength === 0)
    {
        paragraphs.push(memo);
        memo = "";
    }
    return memo + " " + word;
  }, "");
  return paragraphs
}

const paragraphs = getParagraphs(words, 20);
console.log("original string ===>", words);
console.log("paragraphs array ===>", paragraphs);
//below is for display purposes only
let results = document.getElementById('results');
paragraphs.forEach(paragraph => {
  const para = document.createElement("p");
  const node = document.createTextNode(paragraph);
   para.appendChild(node);
   results.appendChild(para);
});

<div id="results">
</div>


答:
```<code>private void Timer1_Tick(object sender, EventArgs e)
{
  this.progressBar1.Increment(1);
  If (progressBar1.Value >= progressBar1.Maximum)
  {
    // do something
  }
}
</code>```

Title: How could I check if progress bar is full and then open an .bat file?


问:
Where can I find MySql 4.0.30 for windows?
I need to adapt our testing server to our production one that is stored on Aruba.
Aruba use MySql 4.0.30 but I can't find them nowhere!
Anybody know where can I find it ? or anybody has the installer stored anywhere?

Davide

答: According to http://lists.mysql.com/mysql/210800 (an email from a MySQL employee) this is a non-public release for customers who are too inflexible to upgrade. It says you can pay for "extended support" to get it.</p>


问:
How to center items in a Recyclerview?
I am using RecyclerView with Cardview items inside it. I set the  GridLayoutManager to show 2 items at each row and I want it to be centered on all phones like this :

expected result

But I have currently these :

Actual result

I tried different poor solutions (paddingLeft...) but it works on phones with bigger screens and doesn't work on smaller phones.

content_main.xml looks like this :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="Rechercher un film"
        android:iconifiedByDefault="false"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="10dp"
        android:layout_height="30dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />

</RelativeLayout>
</code>```

movie_card.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="170dip"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/item_movie_poster"
            android:layout_width="170dip"
            android:layout_height="256dip"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/movie_image_description"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/item_movie_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/item_movie_poster"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dip"
            android:layout_marginTop="5dip"
            android:textSize="15sp"
            android:textAlignment="center"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:textStyle="bold" />

    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</code>```

And app_bar_main.xml which includes the content_main.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
Since you're using GridLayoutManager set card_view.xml parent view width as match_parent i.e.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" //change
android:layout_height="wrap_content"
android:gravity="center"//add this
android:orientation="vertical">
</code>```

Or you can make that RelativeLayout and set child CardView centerInParent to true

Comment in case of any queries

Hope this helps. Happy coding!

Title: How to center items in a Recyclerview?

Body:
I am using RecyclerView with Cardview items inside it. I set the  GridLayoutManager to show 2 items at each row and I want it to be centered on all phones like this :

expected result

But I have currently these :

Actual result

I tried different poor solutions (paddingLeft...) but it works on phones with bigger screens and doesn't work on smaller phones.

content_main.xml looks like this :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:queryHint="Rechercher un film"
        android:iconifiedByDefault="false"
        android:layout_marginTop="65dp"
        android:layout_marginBottom="10dp"
        android:layout_height="30dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/searchView"
        android:scrollbars="vertical"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true" />

</RelativeLayout>

movie_card.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="170dip"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/item_movie_poster"
            android:layout_width="170dip"
            android:layout_height="256dip"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/movie_image_description"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/item_movie_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/item_movie_poster"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dip"
            android:layout_marginTop="5dip"
            android:textSize="15sp"
            android:textAlignment="center"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:textStyle="bold" />

    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

And app_bar_main.xml which includes the content_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

Body:
Since you're using GridLayoutManager set card_view.xml parent view width as match_parent i.e.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" //change
android:layout_height="wrap_content"
android:gravity="center"//add this
android:orientation="vertical">

Or you can make that RelativeLayout and set child CardView centerInParent to true

Comment in case of any queries

Hope this helps. Happy coding!


问:
Method "load" is not defined on the instance but referenced during render error on integrating @syncfusion/ej2-vue-maps package
Configuration:
System: Windows 10
Technology: Vuejs
Node Version: v10.14.1
Npm version: 6.4.1
Description:
Hello, I am using @syncfusion/ej2-vue-maps package to integrate below map in my vuejs project.

I have added following lines of code in main.js file:

```<code>import { MapsPlugin, Marker, MapsTooltip, MapAjax } from '@syncfusion/ej2-vue-maps';
Vue.use(MapsPlugin);
</code>```

After adding above line of code. I created an new file where I added the code to display maps with marker. Here is my Maps.vue file

```<code><template>
  <div>
     <ejs-maps id='container' :load='load' :titleSettings='titleSettings' :zoomSettings='zoomSettings' :useGroupingSeparator='useGroupingSeparator' format='n'>
       <e-layers>
         <e-layer :shapeData='shapeData' :dataSource='dataSource' :shapeSettings='shapeSettings' :markerSettings='markerSettings'></e-layer>
        </e-layers>
      </ejs-maps>
 </div>
</template>

<script>
import { Marker, MapsTooltip, MapAjax } from '@syncfusion/ej2-vue-maps';
import { topPopulation } from './map-data/marker-location.js';
import Template from './marker-temp.vue';

export default {
   data(){
      return{
         useGroupingSeparator: true,
         zoomSettings: {
            enable: false
         },
         titleSettings: {
            text: 'Top 25 populated cities in the world',
            textStyle: {
               size: '16px'
            }
         },
         shapeData: new MapAjax('./map-data/world-map.js'),
         dataSource: topPopulation,
         shapeSettings: {
            fill: '#C3E6ED'
         },
         markerSettings: [
            {
               dataSource: topPopulation,
               visible: true,
               animationDuration: 0,
               shape: 'Circle',
               fill: 'white',
               width: 3,
               border: { width: 2, color: '#285255' },
               tooltipSettings: {
                  template: function () { return {template: Template}; },
                  visible: true,
                  valuePath: 'population',
               }
            }
         ]
      }
   },
   provide: {
      maps: [Marker, MapsTooltip]
   }
}
</script>
</code>```

On running the project I got below error:
Property or method "load" is not defined on the instance but referenced during render.
What value we are getting in load ? Load is not defined in data also, So from where we are getting the load value? Also I have't found any file "marker-temp.vue" after installing library due to which it shows missing file error. Where is it? Please help. Is anything I am missing?

答:
You are missing load in your Data() so you must define load,

You are referencing something that doesn't exist. You must check the documentation of the component you are utilizing and see what kind of structure of load they expect you to give then define it.

```<code>data(){
  return{
    load: ""
  }
}
</code>```

after looking through the documentation,I found this, check this link

Body:
Configuration:
System: Windows 10
Technology: Vuejs
Node Version: v10.14.1
Npm version: 6.4.1
Description:
Hello, I am using @syncfusion/ej2-vue-maps package to integrate below map in my vuejs project.

I have added following lines of code in main.js file:

import { MapsPlugin, Marker, MapsTooltip, MapAjax } from '@syncfusion/ej2-vue-maps';
Vue.use(MapsPlugin);

After adding above line of code. I created an new file where I added the code to display maps with marker. Here is my Maps.vue file

<template>

     <ejs-maps id='container' :load='load' :titleSettings='titleSettings' :zoomSettings='zoomSettings' :useGroupingSeparator='useGroupingSeparator' format='n'>
       <e-layers>
         <e-layer :shapeData='shapeData' :dataSource='dataSource' :shapeSettings='shapeSettings' :markerSettings='markerSettings'></e-layer>
        </e-layers>
      </ejs-maps>

</template>

On running the project I got below error:
Property or method "load" is not defined on the instance but referenced during render.
What value we are getting in load ? Load is not defined in data also, So from where we are getting the load value? Also I have't found any file "marker-temp.vue" after installing library due to which it shows missing file error. Where is it? Please help. Is anything I am missing?

Body:
You are missing load in your Data() so you must define load,

You are referencing something that doesn't exist. You must check the documentation of the component you are utilizing and see what kind of structure of load they expect you to give then define it.

data(){
  return{
    load: ""
  }
}

after looking through the documentation,I found this, check this link


问:
Most straightforward way to cache geocoding data
I am using geopy to get lat/long coordinates for a list of addresses.  All the documentation points to limiting server queries by caching (many questions here, in fact), but few actually give practical solutions.

What is the best way to accomplish this?

This is for a self-contained data processing job I'm working on ... no app platform involved.  Just trying to cut down on server queries as I run through data that I will have seen before (very likely, in my case).

My code looks like this:

```<code>from geopy import geocoders
def geocode( address ):
    # address ~= "175 5th Avenue NYC"
    g = geocoders.GoogleV3()
    cache = addressCached( address )

    if ( cache != False ):
        # We have seen this exact address before,
        # return the saved location
        return cache

    # Otherwise, get a new location from geocoder
    location = g.geocode( address )

    saveToCache( address, location )
    return location

def addressCached( address ):
    # What does this look like?

def saveToCache( address, location ):
    # What does this look like?
</code>```

答:
Here is a simple implementation that uses the python shelve package for transparent and persistent caching:

```<code>import geopy
import shelve
import time

class CachedGeocoder:
    def __init__(self, source = "Nominatim", geocache = "geocache.db"):
        self.geocoder = getattr(geopy.geocoders, source)()
        self.db = shelve.open(geocache, writeback = True)
        self.ts = time.time()+1.1
    def geocode(self, address):
        if not address in self.db:
            time.sleep(max(1 -(time.time() - self.ts), 0))
            self.ts = time.time()
            self.db[address] = self.geocoder.geocode(address)
        return self.db[address]

geocoder = CachedGeocoder()
print geocoder.geocode("San Francisco, USA")
</code>```

It stores a timestamp to ensure that requests are not issued more frequently than once per second (which is a requirement for Nominatim). One weakness is that doesn't deal with timed out responses from Nominatim.

Body:
I am using geopy to get lat/long coordinates for a list of addresses.  All the documentation points to limiting server queries by caching (many questions here, in fact), but few actually give practical solutions.

What is the best way to accomplish this?

This is for a self-contained data processing job I'm working on ... no app platform involved.  Just trying to cut down on server queries as I run through data that I will have seen before (very likely, in my case).

My code looks like this:

from geopy import geocoders
def geocode( address ):
    # address ~= "175 5th Avenue NYC"
    g = geocoders.GoogleV3()
    cache = addressCached( address )

    if ( cache != False ):
        # We have seen this exact address before,
        # return the saved location
        return cache

    # Otherwise, get a new location from geocoder
    location = g.geocode( address )

    saveToCache( address, location )
    return location

def addressCached( address ):
    # What does this look like?

def saveToCache( address, location ):
    # What does this look like?

Body:
Here is a simple implementation that uses the python shelve package for transparent and persistent caching:

import geopy
import shelve
import time

class CachedGeocoder:
    def __init__(self, source = "Nominatim", geocache = "geocache.db"):
        self.geocoder = getattr(geopy.geocoders, source)()
        self.db = shelve.open(geocache, writeback = True)
        self.ts = time.time()+1.1
    def geocode(self, address):
        if not address in self.db:
            time.sleep(max(1 -(time.time() - self.ts), 0))
            self.ts = time.time()
            self.db[address] = self.geocoder.geocode(address)
        return self.db[address]

geocoder = CachedGeocoder()
print geocoder.geocode("San Francisco, USA")

It stores a timestamp to ensure that requests are not issued more frequently than once per second (which is a requirement for Nominatim). One weakness is that doesn't deal with timed out responses from Nominatim.


问:
Angular 7, Ngrx, Rxjs 6 - Accessing state between lazy loaded modules
I am using Angular 7 with Ngrx and Rxjs 6. I got 2 lazy loaded modules A and B which have their own selectors and reducers.

Now, I would like to access the data stored on the module B state from the module A. The problem is that all of the ngrx components of module B get initialized only when the user navigates to the lazy loaded route of B, so if the user first goes to A , attempting to select the state will result in undefined errors because B is not yet initialized.

What would be the best practice in accessing the state of a lazy loaded module in this case?

答: In my opinion his use case is valid and ngrx ought to be able to handle it but it drops state if a reducer is not added to ngrx through the forFeature function because a lazy loaded module is not yet loaded which makes it impossible to retrieve the entire state from a database in the backend and use it as needed in lazy loaded modules.</p>


问:
PHP, javascript, ajax - communication between 2 users
Good day to all.

I need to do this:

When user X press a button user Y sees a photo. Before that user Y sees nothing.

I did this like this: I created a database on a mysql server and created a table with photos and flags. When user X presses the button I send an ajax request and change the flag to the corresponding photo. User Y also sends ajax request every 1 sec to see if anything has changed.

Sounds ok, looks ok, works... it does but to so ok. When 100000 users send 1 ajax request every 1 second the server crashes. First mysql server then apache.

So... my question is is there anyway to do this without so many ajax requests? Something like send the page with a certain "thing" that tells the browser to keep the same socket and send later the image? Something like a stream but instead of images to be html pages/images/whatever.

I know java applet would be a solution but I would need a php(for server side)+js(for client side) solution.

And yes I know that I'll probably get an "you can't" answer but it deserves a try.

答:
What about WebSockets?

edit.
HTTP keep-alive might help.


问:
Add ALT attribute via jquery seems not working as expected
I'm trying to auto assign the alt attribute to images without it. This is my code:

```<code>$(document).ready(function () {
    var attr = $(this).attr('alt');
    if (typeof attr === typeof undefined || attr === false) {
        $('img').each(function () {
            var $img = $(this);
            var filename = $img.attr('src');
            $img.attr('title', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
            $img.attr('alt', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
        });
    }
});
</code>```

I have a dropdown selector with flag images for countries. Until user do not click on the dropdown selector the images are not displayed. I think that this is causing the code to do not work as expected.

If I check the output of the page, for example in Firefox view source code, I can't find any alt attribute added to the images. Meanwhile if I just analize the element in Firefox I see that the alt attribute is correctly added to the img tag.

Why? What's wrong? How should I edit it so that the page always has the alt attributes added to the code soon as it loads? This is important to me for page accessibility.

Thanks in advance.

答:
You are displaying images on selecting dropdown value but jquery script getting executed as soon as DOM is ready.
You need to execute your code on change of drop down, please refer below code

NOTE: assuming YourDropDownId is the id of dropdown element and image alter code is working. You need to put exact id of your dropdwon and if id is not present then refer to different jquery selector to bind the change event handler.

```<code>$(document).ready(function () {
    $('#YourDropDownId').on('change', function(){
        $('img').each(function () {
            var $img = $(this);
            var filename = $img.attr('src');
            var value = filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.'));
            $img.attr('title', value);
            $img.attr('alt', value);
        });
    });
});
</code>```

Body:
I'm trying to auto assign the alt attribute to images without it. This is my code:

$(document).ready(function () {
    var attr = $(this).attr('alt');
    if (typeof attr === typeof undefined || attr === false) {
        $('img').each(function () {
            var $img = $(this);
            var filename = $img.attr('src');
            $img.attr('title', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
            $img.attr('alt', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
        });
    }
});

I have a dropdown selector with flag images for countries. Until user do not click on the dropdown selector the images are not displayed. I think that this is causing the code to do not work as expected.

If I check the output of the page, for example in Firefox view source code, I can't find any alt attribute added to the images. Meanwhile if I just analize the element in Firefox I see that the alt attribute is correctly added to the img tag.

Why? What's wrong? How should I edit it so that the page always has the alt attributes added to the code soon as it loads? This is important to me for page accessibility.

Thanks in advance.

Body:
You are displaying images on selecting dropdown value but jquery script getting executed as soon as DOM is ready.
You need to execute your code on change of drop down, please refer below code

NOTE: assuming YourDropDownId is the id of dropdown element and image alter code is working. You need to put exact id of your dropdwon and if id is not present then refer to different jquery selector to bind the change event handler.

$(document).ready(function () {
    $('#YourDropDownId').on('change', function(){
        $('img').each(function () {
            var $img = $(this);
            var filename = $img.attr('src');
            var value = filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.'));
            $img.attr('title', value);
            $img.attr('alt', value);
        });
    });
});


问:
Game server - high latency
I'm trying to host a Spigot Minecraft 1.12.2 Server using Ubuntu, The server has been properly set up and is working properly, The ping however isn't really great, I am playing from India and the server VM instance region has been set to Germany-Frankfurt, I should be getting anywhere between 130-200ms latency but It's always above 300 or even 1000 at times, I did tracert using windows CMD terminal and the packets seem to go to U.S.A first and then to Germany, I asked several of my friends to ping the server and they all get the same result. How can I fix this? Is there any way to route packets straight to Germany Instead of going to the U.S first?

Made a new Instance in Mumbai Region, India, which is where I live, I'm getting 3 Ping while on the server select menu, but upon joining it jumps to 200.

I expect around 130-160 ping, which is what I get on other servers on that region, Other players who live near Germany are getting high pings, I can't make this server public with a major issue like this.

答:
Probably you're experiencing this issue due to instance's machine type and CPU's count.

As stated in the documentation:

"Outbound or egress traffic from a virtual machine is subject to maximum network egress throughput caps. These caps are dependent on the number of vCPUs that a virtual machine instance has. Each core is subject to a 2 Gbits/second (Gbps) cap for peak performance. Each additional core increases the network cap, up to a theoretical maximum of 16 Gbps for each virtual machine".

Having so little information about your setup i cannot help you further unfortunately.

Please provide more information about your setup and your customer's needs.

For example, who will your customers be? From which country? Is this the reason why you're using an European region for your services while you live in India?

Title: Game server - high latency


问:
Firefox 66.0 and Geckodriver 0.24.0 are not compatible?
Unable to launch Firefox.

Tried with
Firefox 66.0 and Geckodriver  geckodriver 0.24.0

Using Firefox 61.0 and Geckodriver  geckodriver 0.21.0

```<code>FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("webdriver.log.driver", "INFO");
profile.setPreference("webdriver.log.file", targetDir + File.separator + "firefoxSeleniumServer.log");
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv;text/plain");
if(platform.equalsIgnoreCase("linux")) {
FirefoxOptions options = new FirefoxOptions();

profile.setPreference("browser.download.dir",System.getProperty("user.dir")+ File.separator + "target");
System.setProperty("webdriver.gecko.driver", "/geckodriver/geckodriver");
System.setProperty("webdriver.firefox.bin","/usr/bin/firefox/firefox");

options.setCapability(CapabilityType.PLATFORM_NAME,Platform.LINUX);
options.setCapability("marionette", true);
options.setCapability("webdriver.firefox.profile",DesiredCapabilities.firefox());
driver = new FirefoxDriver();
}
</code>```

Session ID: 8d18af2e-b532-4991-af81-d446fb07bb6c
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

Caused by: java.lang.RuntimeException: There was an error in the forked process
org.openqa.selenium.NoSuchSessionException

答: As per this page 'https://github.com/mozilla/geckodriver/releases' v0.24.0' will support 65+ versions also. To overcome these version issues, you can try 'https://github.com/bonigarcia/webdrivermanager' where we don't require to add/ replace exe files for each browser.</p>

Body:
Unable to launch Firefox.

Tried with
Firefox 66.0 and Geckodriver  geckodriver 0.24.0

Using Firefox 61.0 and Geckodriver  geckodriver 0.21.0

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("webdriver.log.driver", "INFO");
profile.setPreference("webdriver.log.file", targetDir + File.separator + "firefoxSeleniumServer.log");
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv;text/plain");
if(platform.equalsIgnoreCase("linux")) {
FirefoxOptions options = new FirefoxOptions();

profile.setPreference("browser.download.dir",System.getProperty("user.dir")+ File.separator + "target");
System.setProperty("webdriver.gecko.driver", "/geckodriver/geckodriver");
System.setProperty("webdriver.firefox.bin","/usr/bin/firefox/firefox");

options.setCapability(CapabilityType.PLATFORM_NAME,Platform.LINUX);
options.setCapability("marionette", true);
options.setCapability("webdriver.firefox.profile",DesiredCapabilities.firefox());
driver = new FirefoxDriver();
}

Session ID: 8d18af2e-b532-4991-af81-d446fb07bb6c
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

Caused by: java.lang.RuntimeException: There was an error in the forked process
org.openqa.selenium.NoSuchSessionException


问:
Is CrudRepository.save(Iterable<S>) is atomic?
I am saving multiple objects using CrudRepository.save(Iterable<S>).

is this operation behaviour is atomic?

What will happen if I save 10 entities and it fails for 6th one?

答:
Behind the seen this is what's happening in case of SimpleJpaRepository save method with Iterable

```<code>@Transactional
public <S extends T> List<S> More save(Iterable<S> entities) {

    List<S> result = new ArrayList<S>();

    if (entities == null) {
        return result;
    }

    for (S entity : entities) {
        result.add(save(entity));
    }

    return result;
}
</code>```

It's worth noting that save with Iterable has changed to saveAll in latest versions
Refer changes for more detail

What will happen if I save 10 entities and it fails for 6th one?

By default CrudRespository will have @Transactional so on case of exception nothing is saved.

In case of handling manually this will work

If you are doing something like this things will be rollback.

```<code>@Transactional(rollbackFor=RuntimeException.class)
public List<Car> saveAllOrNone(List<Car> cars) {
    for(Car car: cars) {
        repo.save(car);
    }
}
</code>```

Body:
Behind the seen this is what's happening in case of SimpleJpaRepository save method with Iterable

@Transactional
public <S extends T> List<S> More save(Iterable<S> entities) {

    List<S> result = new ArrayList<S>();

    if (entities == null) {
        return result;
    }

    for (S entity : entities) {
        result.add(save(entity));
    }

    return result;
}

It's worth noting that save with Iterable has changed to saveAll in latest versions
Refer changes for more detail

What will happen if I save 10 entities and it fails for 6th one?

By default CrudRespository will have @Transactional so on case of exception nothing is saved.

In case of handling manually this will work

If you are doing something like this things will be rollback.

@Transactional(rollbackFor=RuntimeException.class)
public List<Car> saveAllOrNone(List<Car> cars) {
    for(Car car: cars) {
        repo.save(car);
    }
}


问:
How to change space between cells in UICollectionView?
I want to reduce the size between cells in row.
Now it looks like:

I'm trying this, for reduce the size between them:

```<code>let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 2, bottom: 10, right: 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
</code>```

but it doesn't help me. What I do wrong?

答:
(Swift 4)

Click on collection View in storyboard.

on right hand side, click size inspector.

manage and alter the cell size value and you'll figure it out by yourself.

Body:
I want to reduce the size between cells in row.
Now it looks like:

I'm trying this, for reduce the size between them:

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 2, bottom: 10, right: 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

but it doesn't help me. What I do wrong?


问:
Kendo dropdown list popup height not working
In this StackBlitz I have a Kendo for Angular dropdown list with a popup height set to 20px. Still, when I open the dropdown list the popup height remains unchanged. How to make this work?</p>

```<code>@Component({
selector: 'my-app',
template: `
 <kendo-dropdownlist [data]="listItems" [popupSettings]="{ height: 20 }">
 </kendo-dropdownlist>
`
})
export class AppComponent {
  public listItems: Array<string> = ["Item 1", "Item 2", "Item 3", "Item 4"];
}
</code>```

答:
The better way to do that is to use popupClass instead of height. That enables you to define a css class that is executed for the popup. In that class you can define attributes like min-height etc.

```<code>[popupSettings]="{ popupClass: 'myPopupClass' }"
</code>```

See documentation

Edit:

In the above solution it looks like you have to set ViewEncapsulation.None and set the height property in the css.

I found an easier solution:

Looks like you also have to set the 'listHeight'. By default the listHeight is 200px.

Look at this Stackblitz

```<code><kendo-dropdownlist [data]="listItems" [popupSettings]="{ height: 20 }" listHeight="20">
</kendo-dropdownlist>
</code>```

Body:
In this StackBlitz I have a Kendo for Angular dropdown list with a popup height set to 20px. Still, when I open the dropdown list the popup height remains unchanged. How to make this work?

@Component({
selector: 'my-app',
template: `
 <kendo-dropdownlist [data]="listItems" [popupSettings]="{ height: 20 }">
 </kendo-dropdownlist>
`
})
export class AppComponent {
  public listItems: Array<string> = ["Item 1", "Item 2", "Item 3", "Item 4"];
}

Body:
The better way to do that is to use popupClass instead of height. That enables you to define a css class that is executed for the popup. In that class you can define attributes like min-height etc.

[popupSettings]="{ popupClass: 'myPopupClass' }"

See documentation

Edit:

In the above solution it looks like you have to set ViewEncapsulation.None and set the height property in the css.

I found an easier solution:

Looks like you also have to set the 'listHeight'. By default the listHeight is 200px.

Look at this Stackblitz

<kendo-dropdownlist [data]="listItems" [popupSettings]="{ height: 20 }" listHeight="20">
</kendo-dropdownlist>


问:
For each loop does not operate as expected
I have two sheets in excel, one is a board with several cells with numbers inside, and the other is references (that have the numbers in previous board) and i need to write in same line of the references where are the cells located.

image of the first board where are the references

image of the excel sheet that i have to write the location of each reference

my vba code

Example:

The arm8.png is the board and local.png is where i write de localizations of the cells

```<code>Option Explicit

Sub ciclo()

    Dim FindString As String
    Dim Rng As Range
    Dim matrixVal As Range

    Set matrixVal = Sheets("Localizações").Range("B1")
    FindString = matrixVal

    For Each Rng In matrixVal

        If Trim(FindString) <> "" Then

            With Sheets("Arm8").Range("A1:J10")

                Set Rng = .Find(What:=FindString, _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)

                If Not Rng Is Nothing Then
                    'Application.Goto Rng, False
                    'MsgBox Rng.Column & " - " & Rng.Row
                Else
                    MsgBox "Nothing found"
                End If

            End With

            With Sheets("Localizações")
                .Range("C1:C9").Value = Rng.Column
                .Range("D1:D9").Value = Rng.Row
            End With

        End If

    Next Rng

End Sub
</code>```

I expected the output in local.png to be column C and D

2 - 9

2 - 7

2 - 8

2 - 4

5 - 4

7 - 4

5 - 9

9 - 7

9 - 0

答:
Firstly, as I said in my comment, this:

```<code>Set matrixVal = Sheets("Localizações").Range("B1")
</code>```

sets matrixVal as one single cell (B1 to be precise), so your For-Each loop doesn't have any cells to loop through apart from this single cell, so it will only run once.

Second, the FindString needs to be updated inside the loop, otherwise you'll be searching for the same value over and over.

Finally, you shouldn't update the Rng variable inside the loop because you are already using it to loop through a range. You need a second variable of type Range.

Your code should look like:

```<code> Sub ciclo()

    Dim FindString As String
    Dim Rng As Range
    Dim cell As Range
    Dim matrixVal As Range

    Set matrixVal = ThisWorkbook.Worksheets("Localizacoes").Range("B1:B9")

    For Each cell In matrixVal
        FindString = cell.Value

        If Trim(FindString) <> "" Then

            With ThisWorkbook.Worksheets("Arm8").Range("A1:J10")

                Set Rng = .Find(What:=FindString, _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)

                If Not Rng Is Nothing Then
                    With ThisWorkbook.Worksheets("Localizacoes")
                        .Cells(cell.Row, "C").Value = Rng.Column
                        .Cells(cell.Row, "D").Value = Rng.Row
                    End With
                Else
                    MsgBox "Nothing found"
                End If

            End With

        End If

    Next cell

End Sub
</code>```

Body:
I have two sheets in excel, one is a board with several cells with numbers inside, and the other is references (that have the numbers in previous board) and i need to write in same line of the references where are the cells located.

image of the first board where are the references

image of the excel sheet that i have to write the location of each reference

my vba code

Example:

The arm8.png is the board and local.png is where i write de localizations of the cells

Option Explicit

Sub ciclo()

    Dim FindString As String
    Dim Rng As Range
    Dim matrixVal As Range

    Set matrixVal = Sheets("Localizações").Range("B1")
    FindString = matrixVal

    For Each Rng In matrixVal

        If Trim(FindString) <> "" Then

            With Sheets("Arm8").Range("A1:J10")

                Set Rng = .Find(What:=FindString, _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)

                If Not Rng Is Nothing Then
                    'Application.Goto Rng, False
                    'MsgBox Rng.Column & " - " & Rng.Row
                Else
                    MsgBox "Nothing found"
                End If

            End With

            With Sheets("Localizações")
                .Range("C1:C9").Value = Rng.Column
                .Range("D1:D9").Value = Rng.Row
            End With

        End If

    Next Rng

End Sub

I expected the output in local.png to be column C and D

2 - 9

2 - 7

2 - 8

2 - 4

5 - 4

7 - 4

5 - 9

9 - 7

9 - 0

Body:
Firstly, as I said in my comment, this:

Set matrixVal = Sheets("Localizações").Range("B1")

sets matrixVal as one single cell (B1 to be precise), so your For-Each loop doesn't have any cells to loop through apart from this single cell, so it will only run once.

Second, the FindString needs to be updated inside the loop, otherwise you'll be searching for the same value over and over.

Finally, you shouldn't update the Rng variable inside the loop because you are already using it to loop through a range. You need a second variable of type Range.

Your code should look like:

 Sub ciclo()

    Dim FindString As String
    Dim Rng As Range
    Dim cell As Range
    Dim matrixVal As Range

    Set matrixVal = ThisWorkbook.Worksheets("Localizacoes").Range("B1:B9")

    For Each cell In matrixVal
        FindString = cell.Value

        If Trim(FindString) <> "" Then

            With ThisWorkbook.Worksheets("Arm8").Range("A1:J10")

                Set Rng = .Find(What:=FindString, _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)

                If Not Rng Is Nothing Then
                    With ThisWorkbook.Worksheets("Localizacoes")
                        .Cells(cell.Row, "C").Value = Rng.Column
                        .Cells(cell.Row, "D").Value = Rng.Row
                    End With
                Else
                    MsgBox "Nothing found"
                End If

            End With

        End If

    Next cell

End Sub


问:
It is possible to make dynamic html from json ionic
I want to make dynamic html from JSON response coming from server,

For eg: Let say json response from server is

```<code>   param_data: any = {

     "fields": [
     { "type": "text", "name": "firstname", "label": "label", "required": true, "data": "", "frmctrlnm": "labelone" },
     { "type": "button", "name": "firstname", "label": "label two", "required": true, "data": "", "frmctrlnm": "labeltwo" },
     { "type": "input", "name": "Red", "label": "input", "required": true, "data": "", "frmctrlnm": "inputone" },
     { "type": "input", "name": "BLue", "label": "input", "required": true, "data": "", "frmctrlnm": "inputone" },
     { "type": "label", "name": "color_id", "label": "input two", "required": true, "data": "", "frmctrlnm": "inputtwo" },
     { "type": "select", "name": "select", "label": "select", "required": true, "data": "", "frmctrlnm": "select" }

     ]}
</code>```

Based on type coming from server i wants to make html component and on click of submit i want same json with user updated data in the fields.

It is possible to achieve this ?

Thank you in advance!

答:
You can try something like this:</p>

```<code>let htmlString = ``;

param_data.fields.forEach(element => {
  if (element.type == "text") {
    htmlString +=
      `<div class="form-group">
        <label class="control-label col-md-4">
          ${element.label}:
        </label>
        <div class="col-md-8">
          <input type="text" class="form-control"  name="${element.name}" ${element.required == true? 'required':''}>
        </div>
      </div>`
  }
});
</code>```

Body:
I want to make dynamic html from JSON response coming from server,

For eg: Let say json response from server is

   param_data: any = {

     "fields": [
     { "type": "text", "name": "firstname", "label": "label", "required": true, "data": "", "frmctrlnm": "labelone" },
     { "type": "button", "name": "firstname", "label": "label two", "required": true, "data": "", "frmctrlnm": "labeltwo" },
     { "type": "input", "name": "Red", "label": "input", "required": true, "data": "", "frmctrlnm": "inputone" },
     { "type": "input", "name": "BLue", "label": "input", "required": true, "data": "", "frmctrlnm": "inputone" },
     { "type": "label", "name": "color_id", "label": "input two", "required": true, "data": "", "frmctrlnm": "inputtwo" },
     { "type": "select", "name": "select", "label": "select", "required": true, "data": "", "frmctrlnm": "select" }

     ]}

Based on type coming from server i wants to make html component and on click of submit i want same json with user updated data in the fields.

It is possible to achieve this ?

Thank you in advance!

Body:
You can try something like this:

let htmlString = ``;

param_data.fields.forEach(element => {
  if (element.type == "text") {
    htmlString +=
      `<div class="form-group">
        <label class="control-label col-md-4">
          ${element.label}:
        </label>
        <div class="col-md-8">
          <input type="text" class="form-control"  name="${element.name}" ${element.required == true? 'required':''}>
        </div>
      </div>`
  }
});


问:
Is there anything in Xamarin forms which is equivalent to "Path" in WPF?
I'm looking after to embed a vector path data in Image control. WPF has a Control "Path" which takes data and render the image. Is there anything in Xamarin forms to do this?</p>

答:
In a word, no. Xamarin Forms and WPF are fundamentally different at the rendering layer.

WPF is tightly integrated into Direct3D via milcore, which enabled the developers to re-build all windows GUI elements from the ground up (buttons, checkboxes, text blocks etc). This, coupled with templating, is what makes the "P" in WPF so incredibly flexible.

Unfortunately this comes with a huge price: performance. There's no way hand-held devices would be able to provide the bandwidth needed to support such an engine, so Xamarin Forms had to instead provide classes that were implemented using each respective operating system's native GUI controls; in this respect it's closer to WinForms. This meant that the base set of Xamarin Forms controls had to be whatever controls were common to all supported build types i.e. iOS, Android, UWP etc. The bottom line is that anything requiring the kind of fine granularity of Path will probably run too slow on these platforms if implemented in Forms and you'd just have to wind up implementing them natively anyway.

If you want to go down this path yourself then it can certainly be done by creating a custom control in your PCL project based on View (say) and then providing a native renderer for it in each of your targets, i.e. something like this:

```<code>// Android renderer for your custom control
[assembly: ExportRenderer(typeof(YourCustomControl), typeof(YourCustomControlRenderer))]
namespace Your.Project.Namespace
{
    public class YourCustomControlRenderer : VisualElementRenderer<YourCustomControl>
    {
        protected override void OnDraw(Canvas canvas)
        {
            ... etc ...
            canvas.DrawRect(new RectF(drawRect), bkgPaint);
            ... etc ...
        }
    }
}
</code>```

Or, as SushiuHangover points out, you can use a 3rd-party lib which will basically just be doing this anyway.

Body:
In a word, no. Xamarin Forms and WPF are fundamentally different at the rendering layer.

WPF is tightly integrated into Direct3D via milcore, which enabled the developers to re-build all windows GUI elements from the ground up (buttons, checkboxes, text blocks etc). This, coupled with templating, is what makes the "P" in WPF so incredibly flexible.

Unfortunately this comes with a huge price: performance. There's no way hand-held devices would be able to provide the bandwidth needed to support such an engine, so Xamarin Forms had to instead provide classes that were implemented using each respective operating system's native GUI controls; in this respect it's closer to WinForms. This meant that the base set of Xamarin Forms controls had to be whatever controls were common to all supported build types i.e. iOS, Android, UWP etc. The bottom line is that anything requiring the kind of fine granularity of Path will probably run too slow on these platforms if implemented in Forms and you'd just have to wind up implementing them natively anyway.

If you want to go down this path yourself then it can certainly be done by creating a custom control in your PCL project based on View (say) and then providing a native renderer for it in each of your targets, i.e. something like this:

// Android renderer for your custom control
[assembly: ExportRenderer(typeof(YourCustomControl), typeof(YourCustomControlRenderer))]
namespace Your.Project.Namespace
{
    public class YourCustomControlRenderer : VisualElementRenderer<YourCustomControl>
    {
        protected override void OnDraw(Canvas canvas)
        {
            ... etc ...
            canvas.DrawRect(new RectF(drawRect), bkgPaint);
            ... etc ...
        }
    }
}

Or, as SushiuHangover points out, you can use a 3rd-party lib which will basically just be doing this anyway.


问:
How to split a string by comma that is only followed by an alphanumeric character
I am trying to separate a very large .cvs (255 columns) by using a BufferedReader that grabs each line and stores it in a string.

I'd like to be able to split it by a command and letter.
Ex:

1,2,3,5,6 will split into

1 | 2 | 3 | 4 | 5 | 6 | 7

hello,world,good day to you, Sir,test will split into

hello | world | good day to you, Sir | test

notice how I only separated a comma that follows with an alphanumeric. The commas that precede a space are not separated, instead they are part of a sentence.

答:
To split with a comma followed with an alpnanumeric char you may use

```<code>String pattern = ",(?=\\p{Alnum})";
</code>```

Or, if you plan to support any Unicode letters, pass the Pattern.UNICODE_CHARACTER_CLASS

((?U)) option alongside the pattern:

```<code>String pattern = "(?U),(?=\\p{Alnum})";
</code>```

See the RegexPlanet regex demo.

Java demo:

```<code>String s = "hello,world,good day to you, Sir,test,1,2";
String[] result = s.split(",(?=\\p{Alnum})");
for (String r:result) {
    System.out.println(r);
}
</code>```

Output:

```<code>hello
world
good day to you, Sir
test
1
2
</code>```

Body:
To split with a comma followed with an alpnanumeric char you may use

String pattern = ",(?=\\p{Alnum})";

Or, if you plan to support any Unicode letters, pass the Pattern.UNICODE_CHARACTER_CLASS

((?U)) option alongside the pattern:

String pattern = "(?U),(?=\\p{Alnum})";

See the RegexPlanet regex demo.

Java demo:

String s = "hello,world,good day to you, Sir,test,1,2";
String[] result = s.split(",(?=\\p{Alnum})");
for (String r:result) {
    System.out.println(r);
}

Output:

hello
world
good day to you, Sir
test
1
2


问:
Return from two tables in single query
I have a query that inserts into two tables at once (required because of foreign key constraints linking them) and would like to return the result of both inserts at the same level but I am not sure how that would be done, or if it is even possible.

The inserts look like this and work fine:

```<code>with org_b as (
    insert into public.base (
        id,
        organisation_id,
        last_modified_by
    )
    values ('<organisation UUID/>', '<organisation UUID/>', '<user UUID/>')
    returning *
), org_eb as (
    insert into public.entity_base (
        id
    )
    values ('<organisation UUID/>')
    returning *
), org as (
    insert into public.organisation_data (
        id,
        armicus_name
    )
    values ('<organisation UUID/>', 'Stack Overflow')
    returning *
), use_b as (
    insert into public.base (
        id,
        organisation_id,
        last_modified_by
    )
    values ('<user UUID/>', '<organisation UUID/>', '<user UUID/>')
    returning *
), use_eb as (
    insert into public.entity_base (
        id
    )
    values ('<user UUID/>')
    returning *
), use as (
    insert into public.user_account_data (
        id,
        email
    )
    values ('<user UUID/>', 'stack@overflow.com')
    returning *
)
</code>```

What I would like is to return it something like this:

```<code>select to_json(
    select org_b.id, org_b.organisation_id, org_b.created_date, org_b.last_modified_date, org_b.last_modified_by, org_b.armicus_data, org.armicus_name
    from org_b
    join org on org_b.id = org.id
) as organisation, to_json(
    select use_b.id, use_b.organisation_id, use_b.created_date, use_b.last_modified_date, use_b.last_modified_by, use_b.armicus_data, use.email
    from use_b
    join use on use_b.id = use.id
) as user
from org_b
</code>```

But this throws a syntax error, is there a way to achieve this? I can also upload the SQL to create the tables if that would help.

Edited to add SQL to create tables and constraints:

Create base table:

```<code>CREATE TABLE base (
    id uuid PRIMARY KEY,
    organisation_id uuid NOT NULL,
    created_date timestamptz NOT NULL DEFAULT now(),
    last_modified_date timestamptz NOT NUll,
    last_modified_by uuid NOT NULL,
    armicus_data jsonb
);
</code>```

Create entity base:

```<code>CREATE TABLE entity_base (
    id uuid PRIMARY KEY REFERENCES base(id) ON DELETE CASCADE,
    template_id uuid
);
</code>```

Create organisation data:

```<code>CREATE TABLE organisation_data (
    id uuid PRIMARY KEY REFERENCES entity_base(id) ON DELETE CASCADE,
    armicus_name TEXT
);
</code>```

Create user account data:

```<code>CREATE TABLE user_account_data (
    id uuid PRIMARY KEY REFERENCES entity_base(id) ON DELETE CASCADE,
    email text NOT NULL
);
</code>```

Add organisation id foreign key:

```<code>ALTER TABLE base ADD CONSTRAINT base_organisation_id_fkey FOREIGN KEY (organisation_id) REFERENCES organisation_data(id);
</code>```

Add last modified by foreign key:

```<code>ALTER TABLE base ADD CONSTRAINT base_last_modified_by_fkey FOREIGN KEY (last_modified_by) REFERENCES user_account_data(id);
</code>```

答:
You can phrase this as:

```<code>select to_json( (select b.id, b.organisation_id, b.created_date, b.last_modified_date, b.last_modified_by, b.armicus_data, org.armicus_name
                 from org_b b join
                      org o
                      on b.id = o.id
                )
              ) as organisation,
       to_json( (select b.id, b.organisation_id, b.created_date, b.last_modified_date, b.last_modified_by, b.armicus_data, u.email
                 from use_b b join
                      use u
                      on b.id = u.id
                )
              ) as user
from org_b ;
</code>```

Or I would probably write this moving the json conversion to the subquery:

```<code>select (select to_json( (b.id, b.organisation_id, b.created_date, b.last_modified_date, b.last_modified_by, b.armicus_data, org.armicus_name) )
        from org_b b join
             org o
             on b.id = o.id
       ) as organisation,
      (select to_json( (b.id, b.organisation_id, b.created_date, b.last_modified_date, b.last_modified_by, b.armicus_data, u.email) )
       from use_b b join
            use u
            on b.id = u.id
      ) ) as user
from org_b
</code>```

Title: Return from two tables in single query

Body:
I have a query that inserts into two tables at once (required because of foreign key constraints linking them) and would like to return the result of both inserts at the same level but I am not sure how that would be done, or if it is even possible.

The inserts look like this and work fine:

with org_b as (
    insert into public.base (
        id,
        organisation_id,
        last_modified_by
    )
    values ('<organisation UUID/>', '<organisation UUID/>', '<user UUID/>')
    returning *
), org_eb as (
    insert into public.entity_base (
        id
    )
    values ('<organisation UUID/>')
    returning *
), org as (
    insert into public.organisation_data (
        id,
        armicus_name
    )
    values ('<organisation UUID/>', 'Stack Overflow')
    returning *
), use_b as (
    insert into public.base (
        id,
        organisation_id,
        last_modified_by
    )
    values ('<user UUID/>', '<organisation UUID/>', '<user UUID/>')
    returning *
), use_eb as (
    insert into public.entity_base (
        id
    )
    values ('<user UUID/>')
    returning *
), use as (
    insert into public.user_account_data (
        id,
        email
    )
    values ('<user UUID/>', 'stack@overflow.com')
    returning *
)

What I would like is to return it something like this:

select to_json(
    select org_b.id, org_b.organisation_id, org_b.created_date, org_b.last_modified_date, org_b.last_modified_by, org_b.armicus_data, org.armicus_name
    from org_b
    join org on org_b.id = org.id
) as organisation, to_json(
    select use_b.id, use_b.organisation_id, use_b.created_date, use_b.last_modified_date, use_b.last_modified_by, use_b.armicus_data, use.email
    from use_b
    join use on use_b.id = use.id
) as user
from org_b

But this throws a syntax error, is there a way to achieve this? I can also upload the SQL to create the tables if that would help.

Edited to add SQL to create tables and constraints:

Create base table:

CREATE TABLE base (
    id uuid PRIMARY KEY,
    organisation_id uuid NOT NULL,
    created_date timestamptz NOT NULL DEFAULT now(),
    last_modified_date timestamptz NOT NUll,
    last_modified_by uuid NOT NULL,
    armicus_data jsonb
);

Create entity base:

CREATE TABLE entity_base (
    id uuid PRIMARY KEY REFERENCES base(id) ON DELETE CASCADE,
    template_id uuid
);

Create organisation data:

CREATE TABLE organisation_data (
    id uuid PRIMARY KEY REFERENCES entity_base(id) ON DELETE CASCADE,
    armicus_name TEXT
);

Create user account data:

CREATE TABLE user_account_data (
    id uuid PRIMARY KEY REFERENCES entity_base(id) ON DELETE CASCADE,
    email text NOT NULL
);

Add organisation id foreign key:

ALTER TABLE base ADD CONSTRAINT base_organisation_id_fkey FOREIGN KEY (organisation_id) REFERENCES organisation_data(id);

Add last modified by foreign key:

ALTER TABLE base ADD CONSTRAINT base_last_modified_by_fkey FOREIGN KEY (last_modified_by) REFERENCES user_account_data(id);

Body:
You can phrase this as:

select to_json( (select b.id, b.organisation_id, b.created_date, b.last_modified_date, b.last_modified_by, b.armicus_data, org.armicus_name
                 from org_b b join
                      org o
                      on b.id = o.id
                )
              ) as organisation,
       to_json( (select b.id, b.organisation_id, b.created_date, b.last_modified_date, b.last_modified_by, b.armicus_data, u.email
                 from use_b b join
                      use u
                      on b.id = u.id
                )
              ) as user
from org_b ;

Or I would probably write this moving the json conversion to the subquery:

select (select to_json( (b.id, b.organisation_id, b.created_date, b.last_modified_date, b.last_modified_by, b.armicus_data, org.armicus_name) )
        from org_b b join
             org o
             on b.id = o.id
       ) as organisation,
      (select to_json( (b.id, b.organisation_id, b.created_date, b.last_modified_date, b.last_modified_by, b.armicus_data, u.email) )
       from use_b b join
            use u
            on b.id = u.id
      ) ) as user
from org_b


问:
What all detail will get from youtube api by just passing forUsername param
I need to fetch all possible user details of a user by just providing a username from youtube API. I need to know the response </p>

```<code>forUsername
</code>```

答:
Answer: There is no API that will allow you type a username from YouTube and get the users details back.

Possible alternative

However if you have the user in question logged in though Oauth2 you can use one of the following options.

userinfo endpoint

If you have a user login using Oauth2 then you can request profile scope and this will allow you to use the userinfo endpoint to request information about this user.  This is part of the open id connect standard claim response

people.get me

You can also use the Google peole api to get information back about the currently authenticated user people.get

```<code>{
 "kind": "plus#person",
 "etag": "\"4DZKD8nJom0F9AKh7PGs_B0kK-A/9QJ_cErg4m2KU4Yr_BYLRInY36g\"",
 "emails": [
  {
   "value": "xxxxx@gmail.com",
   "type": "account"
  }
 ],
 "id": "117200475572775346",
 "displayName": "Linda Lawton",
 "name": {
  "familyName": "Lawton",
  "givenName": "Linda"
 },
 "image": {
  "url": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/s50/photo.jpg",
  "isDefault": false
 },
 "language": "en"
}
</code>```

Body:
I need to fetch all possible user details of a user by just providing a username from youtube API. I need to know the response

forUsername

Body:
Answer: There is no API that will allow you type a username from YouTube and get the users details back.

Possible alternative

However if you have the user in question logged in though Oauth2 you can use one of the following options.

userinfo endpoint

If you have a user login using Oauth2 then you can request profile scope and this will allow you to use the userinfo endpoint to request information about this user.  This is part of the open id connect standard claim response

people.get me

You can also use the Google peole api to get information back about the currently authenticated user people.get

{
 "kind": "plus#person",
 "etag": "\"4DZKD8nJom0F9AKh7PGs_B0kK-A/9QJ_cErg4m2KU4Yr_BYLRInY36g\"",
 "emails": [
  {
   "value": "xxxxx@gmail.com",
   "type": "account"
  }
 ],
 "id": "117200475572775346",
 "displayName": "Linda Lawton",
 "name": {
  "familyName": "Lawton",
  "givenName": "Linda"
 },
 "image": {
  "url": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/s50/photo.jpg",
  "isDefault": false
 },
 "language": "en"
}