答:
Try with lodash

```<code>var result = _.flatten(data.groups.map( r => r.contactgroups))
              .map(r => ({ gsm: r.contact.gsm, sender: "ifelse", message: "test" })
);

console.log(result);
</code>```

Update #2 - With filter

```<code>var result = _.flatten(_.filter(data.groups,{'select': true }).map( r => r.contactgroups))
              .map(r => ({ gsm: r.contact.gsm, sender: "ifelse", message: "test" })
);

console.log(result);
</code>```

Title: Conversion of Array and objects to bulk insert in mysql Sequelize + Nodejs

Body:
This is my json object:

    {
    "groups":

 [
        {
            "id": 1,
            "groupname": "Angular",
            "createdAt": "2017-12-05T09:36:05.000Z",
            "updatedAt": "2017-12-05T09:36:05.000Z",
            "contactgroups": [
            {
                "id": 1,
                "contact":
                {
                    "gsm": "12345"
                }
            },
            {
                "id": 3,
                "contact":
                {
                    "gsm": "54321"
                }
            },
            {
                "id": 4,
                "contact":
                {
                    "gsm": "99999"
                }
            }],
            "select": true
        },
        {
            "id": 2,
            "groupname": "React",
            "createdAt": "2017-12-05T09:36:10.000Z",
            "updatedAt": "2017-12-05T09:36:10.000Z",
            "contactgroups": [
            {
                "id": 2,
                "contact":
                {
                    "gsm": "66666"
                }
            },
            {
                "id": 5,
                "contact":
                {
                    "gsm": "54321"
                }
            }],
            "select": true
        },
        {
            "id": 3,
            "groupname": "Vue",
            "createdAt": "2017-12-05T09:36:15.000Z",
            "updatedAt": "2017-12-05T09:36:15.000Z",
            "contactgroups": [
            {
                "id": 6,
                "contact":
                {
                    "gsm": "12345"
                }
            }]
        },
     ],
    "sender": "ifelse",
    "message": "test"
}

I want to convert above object like this:

[
    {"gsm": 12345, "sender": "ifelse", "message": "test"},
    {"gsm": 54321, "sender": "ifelse", "message": "test"},
    {"gsm": 99999, "sender": "ifelse", "message": "test"},
    {"gsm": 66666, "sender": "ifelse", "message": "test"},
    {"gsm": 54321, "sender": "ifelse", "message": "test"},
    {"gsm": 12345, "sender": "ifelse", "message": "test"},

]

Then only i am able to bulk insert in sequelize.

How to do this using for or foreach or any other functions? to done this stuff?

is foreach better? is it possible to do with map?

I want my final json object, then only sequelize allowed to bulk create.

Ps: I want "select": true json gsm numbers only

Body:
Try with lodash

var result = _.flatten(data.groups.map( r => r.contactgroups))
              .map(r => ({ gsm: r.contact.gsm, sender: "ifelse", message: "test" })
);

console.log(result);

Update #2 - With filter

var result = _.flatten(_.filter(data.groups,{'select': true }).map( r => r.contactgroups))
              .map(r => ({ gsm: r.contact.gsm, sender: "ifelse", message: "test" })
);

console.log(result);


来源: stackexchange

问:
NotFoundHttpException in laravel Auth login
i can't login with Auth in laravel i got an error NotFoundHttpException
my form for login

```<code><form id="login-form" method="POST" action="{{ route('login') }}">
      {{ csrf_field() }}
</code>```

My file Router.php

```<code>public function auth(){
        // Authentication Routes...
        $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('login', 'Auth\LoginController@login');
        $this->post('logout', 'Auth\LoginController@logout')->name('logout');
}
</code>```

My route:

```<code>Route::group(['middleware' => ['auth']], function () {
 Route::get('home', 'NavmenuController@menuright')->name('home');
}
Auth::routes();
Route::group(['middleware' => ['guest']], function () {
    Route::get('/', function () {
        return view('auth.login');
    });
});
</code>```

答:
If you use the native Auth of laravel then just add this line in routes.php it will handle all routes of authentications

Auth::routes();

ContentLicense: CC BY-SA 3.0

Body:
i can't login with Auth in laravel i got an error NotFoundHttpException
my form for login

<form id="login-form" method="POST" action="{{ route('login') }}">
      {{ csrf_field() }}

My file Router.php

public function auth(){
        // Authentication Routes...
        $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('login', 'Auth\LoginController@login');
        $this->post('logout', 'Auth\LoginController@logout')->name('logout');
}

My route:

Route::group(['middleware' => ['auth']], function () {
 Route::get('home', 'NavmenuController@menuright')->name('home');
}
Auth::routes();
Route::group(['middleware' => ['guest']], function () {
    Route::get('/', function () {
        return view('auth.login');
    });
});


问:
why PHP compose/autoload ‘s performance so lowly?
recently I take a old project to rebuild.

I find the old source is so bad And I decide to reconsitution All project.

I try rewrite one module to test.

finnally I have Done coding and running this code in PHP5.6 environment and use xhprof to test performance to compare with old source.

but the new code's performance is not promote obviously. even cut down...

I find Top consume what is compose's autoload.

why??

OLD_SOURCE:

wt(wall time) 1,056,607 µs

cpu(cpu time) 370,198 µs

mu(memory useage) 6,342,688 bytes

NEW_SOURCE:

wt(wall time) 1,333,805 µs

cpu(cpu time) 868,354 µs

mu(memory useage) 3,668,944 bytes

As described.

In new Source

wallt time is up.

cpu time is up.

memory useage is down.

In details:

PDOStatement::execute

    181,289 µs

Composer\Autoload\includeFile@1

    156,924 µs

Composer\Autoload\includeFile

    134,179 µs

file_exists

    104,139 µs

In new code,I used MySQL PDO.

In old code,Is use MySQLi.

I can understand MySQLi fast to PDO.

but why

Composer\Autoload\includeFile@1
Composer\Autoload\includeFile

occupy more time to effected code??

and i find the func file_exists who is in Composer\Autoload\ClassLoader::findFileWithExtension

top3/4 question func in composer....

答:
i find change opcache's setting

; Allow file existence override (file_exists, etc.) performance feature.
opcache.enable_file_override=1

can improve my code.
use before:

wall time: 1,300,687 µs

cpu time: 759,489 µs

use after:

wall time: 771,002 µs

cpu time: 429,664 µs

amazing@_@


问:
jQuery result beign overwritten by the info sent from the GET Method
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

```<code><div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
</code>```

Html of the modal:

```<code>@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">Distrito</label>
                <div class="col-md-10">
                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                </div>
            </div>
            {... more elements}
       </div>
</form>
</code>```

GET Method:

```<code>    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }
</code>```

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

```<code><script type="text/javascript">

    var wasclicked = 0;
    var $this = this;

    $(document).ready(function () {

        document.getElementById("modalbutton").onclick = function () {
            //is AddNew Store button is hitted, this var = 1
            wasclicked = 1;
        };

        $('#modal-action-store').on('hidden.bs.modal', function () {
            //global.wasclicked = 0;
            wasclicked = 0;
            $(this).removeData('bs.modal');
        });

        $('#modal-action-store').on('shown.bs.modal', function (e) {
            console.log($('#DistrictID').length);
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            };
        });
    });
</script>
</code>```

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

```<code>  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
</code>```

And this line is lost:

```<code>var items = "<option value='0'>-- Seleccione Distrito --</option>";
</code>```

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

答:
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.

```<code>    @model Application.Models.ApplicationviewModels.StoreIndexData
    @using Application.Models

    <form asp-action="Create" role="form">
            @await Html.PartialAsync("_ModalHeader", new ModalHeader
        { Heading = String.Format("Actualización de Modelo: Tiendas") })

            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="modal-body form-horizontal">
                <div class="form-group">
                    <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                    <div class="col-md-10">
                        <select asp-for="DepartmentID" class="form-control"
                                asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">Distrito</label>
                    <div class="col-md-10">
                        <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                                asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                    </div>
                </div>
                {... more elements}
           </div>
    </form>

<script type="text/javascript">

    $(document).ready(function () {
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            }
    });

</script>
</code>```

PS: Default option can be also be used. refer the below code.

```<code><div class="form-group">
 <label class="col-md-2 control-label">Distrito</label>
  <div class="col-md-10">
   <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
     <option value='0'>-- Seleccione Distrito --</option>
  </select>
 </div>
</div>
</code>```

Body:
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

              NEW STORE

Html of the modal:

@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>

                Distrito

                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>

            {... more elements}

</form>

GET Method:

    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"

And this line is lost:

var items = "<option value='0'>-- Seleccione Distrito --</option>";

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

Body:
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.

    @model Application.Models.ApplicationviewModels.StoreIndexData
    @using Application.Models

    <form asp-action="Create" role="form">
            @await Html.PartialAsync("_ModalHeader", new ModalHeader
        { Heading = String.Format("Actualización de Modelo: Tiendas") })

            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="modal-body form-horizontal">
                <div class="form-group">
                    <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                    <div class="col-md-10">
                        <select asp-for="DepartmentID" class="form-control"
                                asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-2 control-label">Distrito</label>
                    <div class="col-md-10">
                        <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                                asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                    </div>
                </div>
                {... more elements}
           </div>
    </form>

<script type="text/javascript">

    $(document).ready(function () {
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            }
    });

</script>

PS: Default option can be also be used. refer the below code.

<div class="form-group">
 <label class="col-md-2 control-label">Distrito</label>
  <div class="col-md-10">
   <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
     <option value='0'>-- Seleccione Distrito --</option>
  </select>
 </div>
</div>


问:
Silencing libcurl/pycurl PUT and POST
I have a python script which does a bunch of PUTs and POSTs, and when they are successful curl will output the updated html to stdout. I was wondering if there was a way to keep it from doing this? I don't really care about this information, so sending it to a file isn't necessary, but that seems to be the only solution I can find.</p>

答:
Try setting the WRITEFUNCTION option in the Curl object.

```<code>from StringIO import StringIO
body = StringIO()
(...)
c.setopt(c.WRITEFUNCTION, body.write)
</code>```

Full example can be seen in curl CVS repository.

ContentLicense: CC BY-SA 2.5

Title: Silencing libcurl/pycurl PUT and POST

Body:
Try setting the WRITEFUNCTION option in the Curl object.

from StringIO import StringIO
body = StringIO()
(...)
c.setopt(c.WRITEFUNCTION, body.write)

Full example can be seen in curl CVS repository.


问:
how to disable rsh and rlogin service on debian 7.8
I want to disable rsh and rlogin. I have disable 513 and 154 port in iptables,but I still can login with rsh on another host.I'm working on Debian7.8 32bit

my /etc/inetd.conf is here

```<code># /etc/inetd.conf:  see inetd(8) for further informations.
#
# Internet superserver configuration database
#
#
# Lines starting with "#:LABEL:" or "#<off>#" should not
# be changed unless you know what you are doing!
#
# If you want to disable an entry so it isn't touched during
# package updates just comment it out with a single '#' character.
#
# Packages should modify this file by using update-inetd(8)
#
# <service_name> <sock_type> <proto> <flags> <user> <server_path> <args>
#
#:INTERNAL: Internal services
#discard        stream  tcp nowait  root    internal
#discard        dgram   udp wait    root    internal
#daytime        stream  tcp nowait  root    internal
#time       stream  tcp nowait  root    internal

#:STANDARD: These are standard services.

#:BSD: Shell, login, exec and talk are BSD protocols.

#:MAIL: Mail, news and uucp services.

#:INFO: Info services

#:BOOT: TFTP service is provided primarily for booting.  Most sites
#       run this only on machines acting as "boot servers."

#:RPC: RPC based services

#:HAM-RADIO: amateur-radio services

#:OTHER: Other services
#<off># netbios-ssn stream  tcp nowait  root    /usr/sbin/tcpd  /usr/sbin/smbd
swat        stream  tcp nowait.400  root    /usr/sbin/tcpd  /usr/sbin/swat
#<off># sane-port   stream  tcp nowait  saned:saned /usr/sbin/saned saned
</code>```

答:
Modify the disable field in the configuration file /etc/xinetd.d/rlogin and /etc/xinetd.d/rsh
Then use the command service xinetd restart to restart the xinetd service

Body:
I want to disable rsh and rlogin. I have disable 513 and 154 port in iptables,but I still can login with rsh on another host.I'm working on Debian7.8 32bit

my /etc/inetd.conf is here

# /etc/inetd.conf:  see inetd(8) for further informations.
#
# Internet superserver configuration database
#
#
# Lines starting with "#:LABEL:" or "#<off>#" should not
# be changed unless you know what you are doing!
#
# If you want to disable an entry so it isn't touched during
# package updates just comment it out with a single '#' character.
#
# Packages should modify this file by using update-inetd(8)
#
# <service_name> <sock_type> <proto> <flags> <user> <server_path> <args>
#
#:INTERNAL: Internal services
#discard        stream  tcp nowait  root    internal
#discard        dgram   udp wait    root    internal
#daytime        stream  tcp nowait  root    internal
#time       stream  tcp nowait  root    internal

#:STANDARD: These are standard services.

#:BSD: Shell, login, exec and talk are BSD protocols.

#:MAIL: Mail, news and uucp services.

#:INFO: Info services

#:BOOT: TFTP service is provided primarily for booting.  Most sites
#       run this only on machines acting as "boot servers."

#:RPC: RPC based services

#:HAM-RADIO: amateur-radio services

#:OTHER: Other services
#<off># netbios-ssn stream  tcp nowait  root    /usr/sbin/tcpd  /usr/sbin/smbd
swat        stream  tcp nowait.400  root    /usr/sbin/tcpd  /usr/sbin/swat
#<off># sane-port   stream  tcp nowait  saned:saned /usr/sbin/saned saned


问:
Converting unicode not working in c#
I am trying to convert unicode character in c# but it is not working

code:

```<code>using System;
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace test_request
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string unicode = "Not Your Boyfriend's Tunic";
            string str = System.Uri.UnescapeDataString(unicode);

            Console.WriteLine (str);
        }
    }
}
</code>```

Ouput:

```<code>Not Your Boyfriend's Tunic
</code>```

But expected output is this

Expected output:

```<code>Not Your Boyfriend's Tunic
</code>```

答:
try this</p>

```<code>using System;
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace test_request
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string unicode = "Not Your Boyfriend's Tunic";
            string str = System.Web.HttpUtility.HtmlDecode(unicode);
            Console.WriteLine (str);
        }
    }
}
</code>```

Title: Converting unicode not working in c#

Body:
I am trying to convert unicode character in c# but it is not working

code:

using System;
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace test_request
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string unicode = "Not Your Boyfriend's Tunic";
            string str = System.Uri.UnescapeDataString(unicode);

            Console.WriteLine (str);
        }
    }
}

Ouput:

Not Your Boyfriend's Tunic

But expected output is this

Expected output:

Not Your Boyfriend's Tunic

Body:
try this

using System;
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace test_request
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string unicode = "Not Your Boyfriend&#39;s Tunic";
            string str = System.Web.HttpUtility.HtmlDecode(unicode);
            Console.WriteLine (str);
        }
    }
}


问:
ora-01036 illegal variable name/number c#
help me please

I get an error when fetching data for the date range

```<code>DataTable dt = new DataTable();

       StringBuilder sb = new StringBuilder("SELECT (select dep_title from hr.departments dp where dp.dep_id = d.dep_id) as title,    (SELECT COUNT(*) FROM esd.DOCUMENTS T");
       sb.Append("WHERE T.DEP_ID = D.DEP_ID");
       sb.Append("and t.systarix between");
       sb.Append("to_date(':FROM_DATE', 'MM.DD.YYYY') And");
       sb.Append("to_date(':TO_DATE', 'MM.DD.YYYY')) AS SAY");
       sb.Append("FROM HR.DEPARTMENTS D");

       command.CommandText = sb.ToString();

       command.Parameters.Add("FROM_DATE", OracleType.VarChar);
       command.Parameters["FROM_DATE"].Value = DE_from.DateTime.Date;
       command.Parameters.Add("TO_DATE", OracleType.VarChar);
       command.Parameters["TO_DATE"].Value = DE_to.DateTime.Date;

       dt.Load(command.ExecuteReader());

       gridControl1.DataSource = dt;
</code>```

Error

ora-01036 illegal variable name/number

答:
Here is what your Query looks like also how come you do not close the opening ( in your Sub Select. I would recommend reading up on some basic Sql Selects. Oracle has very good documentation in regards to Syntax.

Also read up on how to properly construct / format a Sub-Query

look at the fields in the select I formatted it so you can see your original query you build using StringBuilder.

```<code>SELECT
(
    select dep_title from hr.departments dp where dp.dep_id = d.dep_id) as title,
    (
        SELECT COUNT(*) FROM esd.DOCUMENTS TWHERE T.DEP_ID = D.DEP_IDand t.systarix
        betweento_date(':FROM_DATE', 'MM.DD.YYYY') Andto_date(':TO_DATE', 'MM.DD.YYYY')
    ) AS SAYFROM HR.DEPARTMENTS D
</code>```

Your errors in right off the bat because of the spacing " " you didn't add are

TWHERE this should  be T WHERE

D.DEP_IDand t.systarix this should be D.DEP_ID and t.systarix

betweento_date this should be between to_date

AS SAYFROM this should be AS SAY FROM

I would suggest / recommend creating your Select Query's in the Oracle Developer and executing them first. From there once you get the query working, convert the query into a Stored Procedure.

Body:
help me please

I get an error when fetching data for the date range

DataTable dt = new DataTable();

       StringBuilder sb = new StringBuilder("SELECT (select dep_title from hr.departments dp where dp.dep_id = d.dep_id) as title,    (SELECT COUNT(*) FROM esd.DOCUMENTS T");
       sb.Append("WHERE T.DEP_ID = D.DEP_ID");
       sb.Append("and t.systarix between");
       sb.Append("to_date(':FROM_DATE', 'MM.DD.YYYY') And");
       sb.Append("to_date(':TO_DATE', 'MM.DD.YYYY')) AS SAY");
       sb.Append("FROM HR.DEPARTMENTS D");

       command.CommandText = sb.ToString();

       command.Parameters.Add("FROM_DATE", OracleType.VarChar);
       command.Parameters["FROM_DATE"].Value = DE_from.DateTime.Date;
       command.Parameters.Add("TO_DATE", OracleType.VarChar);
       command.Parameters["TO_DATE"].Value = DE_to.DateTime.Date;

       dt.Load(command.ExecuteReader());

       gridControl1.DataSource = dt;

Error

ora-01036 illegal variable name/number

Body:
Here is what your Query looks like also how come you do not close the opening ( in your Sub Select. I would recommend reading up on some basic Sql Selects. Oracle has very good documentation in regards to Syntax.

Also read up on how to properly construct / format a Sub-Query

look at the fields in the select I formatted it so you can see your original query you build using StringBuilder.

SELECT
(
    select dep_title from hr.departments dp where dp.dep_id = d.dep_id) as title,
    (
        SELECT COUNT(*) FROM esd.DOCUMENTS TWHERE T.DEP_ID = D.DEP_IDand t.systarix
        betweento_date(':FROM_DATE', 'MM.DD.YYYY') Andto_date(':TO_DATE', 'MM.DD.YYYY')
    ) AS SAYFROM HR.DEPARTMENTS D

Your errors in right off the bat because of the spacing " " you didn't add are

TWHERE this should  be T WHERE

D.DEP_IDand t.systarix this should be D.DEP_ID and t.systarix

betweento_date this should be between to_date

AS SAYFROM this should be AS SAY FROM

I would suggest / recommend creating your Select Query's in the Oracle Developer and executing them first. From there once you get the query working, convert the query into a Stored Procedure.


问:
multi-repository graphql types with local npm link
Given 2 repositories user-repo and project-repo, I define UserType in the user-repo, and in package.json of project-repo I do this:

```<code>"dependencies": {
    "user-repo": "git+ssh://git@github.com/me/user-repo"
}
</code>```

and everything works (UserType loads in project-repo).
However if I link the repo locally like so:

```<code>"dependencies": {
    "user-repo": "file:../../user-repo"
}
</code>```

UserType instanceof GraphQLObjectType returns false. And it's only the graphql types that are acting up. Everything else like models is getting loaded just fine.

I've tried npm linking (npm link user-repo), doing it both the require and import ways, and it didn't help.
Any ideas?

答:
This problem was also discussed in graphql-js issue tracker:

https://github.com/graphql/graphql-js/issues/1091#issuecomment-349874772

Answer by FB developer @leebyron:

Unfortunately npm link is pretty broken, though I'm surprised using a file path as a dependency didn't work for you.

This issue occurs when there are multiple instances of graphql-js in your node_modules directory. npm-link works by creating symlink to another directory, if that other directory also has a node_modules folder with graphql-js within it, then you'll have multiple copies.

When I develop in this way, I usually set up a script which cp's my sub-project's built source directly into the main project's node_modules directory, avoiding any filesystem symlinking hyjinx.

We ended up doing this: common code is no longer a npm package, we use symlink to map common code directory in each application directory and import/require same way as any application module.

Hint for those using docker: you will not be able to put common code into the container this way, docker forbids symlinks. To go around this you can copy the common code in the app temporary directory, build container and remove temporary directory afterwards.

Body:
Given 2 repositories user-repo and project-repo, I define UserType in the user-repo, and in package.json of project-repo I do this:

"dependencies": {
    "user-repo": "git+ssh://git@github.com/me/user-repo"
}

and everything works (UserType loads in project-repo).
However if I link the repo locally like so:

"dependencies": {
    "user-repo": "file:../../user-repo"
}

UserType instanceof GraphQLObjectType returns false. And it's only the graphql types that are acting up. Everything else like models is getting loaded just fine.

I've tried npm linking (npm link user-repo), doing it both the require and import ways, and it didn't help.
Any ideas?


问:
How do I set the "success" function for multiple ajax requests?
How can I set ajax success for all requests done?

```<code>$.ajax({
  success: function(){ clicked = false;}
});

$('.button').click(function(){
   $.post('file.php',{},function(){});
   $.post('file.php',{},function(){});
   $.post('file.php',{},function(){});
});
</code>```

答:
You can use ajaxSetup() to specify default parameters for ajax calls:

```<code>$.ajaxSetup({
  success: function(){ clicked = false; }
});
</code>```

Body:
How can I set ajax success for all requests done?

$.ajax({
  success: function(){ clicked = false;}
});

$('.button').click(function(){
   $.post('file.php',{},function(){});
   $.post('file.php',{},function(){});
   $.post('file.php',{},function(){});
});

Body:
You can use ajaxSetup() to specify default parameters for ajax calls:

$.ajaxSetup({
  success: function(){ clicked = false; }
});


问:
Navigation Bar Failure
So I have an navigation bar for my website that is pretty basic, you click on the word and it takes you to that page. Well after putting a drop down on my page the navigation menu suddenly stopped working. Can anyone see a problem here that I am missing that would allowing the navigation menu to suddenly stop working after a drop down menu occurs?

<!DOCTYPE html>

        Welcome to All About History

Home

About Me

People in History

Contact Me

```

答:
You can also use visibility:hidden property instead of z-index:-1. It also works. It's just a another approach to fix it.

```<code>to {
opacity: 0;
visibility:hidden;
}
</code>```

Title: Navigation Bar Failure

Body:
You can also use visibility:hidden property instead of z-index:-1. It also works. It's just a another approach to fix it.

to {
opacity: 0;
visibility:hidden;
}


问:
Trouble generating TopoJSON to use with D3's Choropleth example
So, I've been following this tutorial https://bl.ocks.org/mbostock/4060606. Just copying and pasting his code directly allows me to see this functionality in action. However, I would like to do the same thing but at the state scale rather than the whole country. So I went to the census bureau's website and downloaded a shapefile for the counties of Missoui, but I'm having difficulty recreating Mike's TopoJSON file. In fact, I've been at this for days, messing around with TopoJSON, but all of the examples I've found use the deprecated topojson command line tools. Since that doesn't exist anymore, I've been forced to figure out for myself how to generate in the same TopoJSON format, but with no luck. I simply cannot get a Shapefile into the same TopoJSON format that Mike uses in this tutorial.

So here is how I've been doing it. I'm getting my Shapefile from this website https://www.census.gov/geo/maps-data/data/cbf/cbf_counties.html and going to the Census 2000 tab (because I don't know how else to get only the counties for Missouri from this website) then selecting and downloading Missouri. I then unzip the downloaded file, then move the .shp and .dbf files to a separate folder. Then I run this command to produce the GeoJSON file:

```<code>shp2json c029_d00 -o missouri_geo.json
</code>```

Then this command to make the TopoJSON file

```<code>geo2topo missouri_geo.json > missouri_topo.json
</code>```

When I compare the format of my TopoJSON file to Mike's TopoJSON file, they are kind of similar, but there seems to be a bunch of missing formatting in my TopoJSON file. I understand that since my file is made from the Shapefile of just Missouri, that already there will be missing data, but I thought that my TopoJSON file would have attributes like the 'id' attribute that contains the FIPS codes for the counties, but my file does not have that. I want to figure out the process to convert a Shapefile into a TopoJSON file that can be used with Mike's code from his example, but I can't seem to figure it out.

Note my javascript and html code is exactly the same as Mike's in his example. In my TopoJSON file, I changed the line after "objects":{ to "counties" to match with the line in the javascript code us.objects.counties. When I run my code and inspect it, I do not receive any errors, but nothing shows up. I do not see anything in my browser.

Any help is much appreciated.

答:
There are a couple potential challenges in replicating this map for a single state and it appears you have run into a few of them. You will need to deviate from the example more than you have.

First, the geographic data your are downloading is composed of latitude longitude pairs - the geographic data the example uses is a pre-projected topojson that is sized to fit in a 960x600 Cartesian plane. You will need to either pre-project your data as well (similar to command line cartography part 1) or project your data on the fly within your block using a geoPath and a geoProjection. Mike does use a geoProjection in his block, a null geoProjection, the default geoProjection for a geoPath. The null projection simply takes coordinates in the json and uses them as svg coordinates with no transform.

Projection issues are probably the most common cause of seeing neither features nor errors. Since you didn't specify a projection, the features are likely rendered off screen. As the continental US sits in the western hemisphere, longitude values are negative - the US will be drawn to the left of the origin, ie off the screen, since you are using a null projection.

The second potential issue for you is that your data has different attributes than the example:

I thought that my TopoJSON file would have attributes like the 'id'
  attribute that contains the FIPS codes for the counties

The feature attributes of your topojson:

```<code>"properties":{"AREA":0.140669542963654,
"PERIMETER":1.69104063251173,
"CO29_D00_":2,
"CO29_D00_I":1,
"STATE":"29",
"COUNTY":"045",
"NAME":"Clark",
"LSAD":"06",
"LSAD_TRANS":"County"}}
</code>```

Are derived from the shapefile:

Since you are using a different source than Mike, the attributes of the data might be different. As the source doesn't have a FIPS ID you cannot make the join between your non-geographic data and your geographic features as in the example. However, there is a not too difficult solution:

Create a FIPS code from the data you do have

From the NOAA (most succinct definition I found):

The first two digits are for the State and the last three identify the County, or county equivalent. So, each State has its own 2-digit number, and each County within the state has its own 3-digit number, which are combined into a 5-digit number to uniquely identify every US county. (source)

You have a number representing state and county - it's a safe bet that this is your FIPS county code when combined. You could combine them in making your geo/topojson, you could create a new property just before drawing the geojson features:

```<code>var features = topojson.feature(us, us.objects.counties).features;
features.forEach(function(d) {
   d.FIPS = "" + d.properties.STATE + d.properties.COUNTY;
})
</code>```

or you could concatenate string and county when filling the feature:

```<code>.attr("fill", function(d) { return color(d.rate = unemployment.get(
""+d.properties.STATE+d.properties.COUNTY)); })
</code>```

Here's what that might look like.

Body:
So, I've been following this tutorial https://bl.ocks.org/mbostock/4060606. Just copying and pasting his code directly allows me to see this functionality in action. However, I would like to do the same thing but at the state scale rather than the whole country. So I went to the census bureau's website and downloaded a shapefile for the counties of Missoui, but I'm having difficulty recreating Mike's TopoJSON file. In fact, I've been at this for days, messing around with TopoJSON, but all of the examples I've found use the deprecated topojson command line tools. Since that doesn't exist anymore, I've been forced to figure out for myself how to generate in the same TopoJSON format, but with no luck. I simply cannot get a Shapefile into the same TopoJSON format that Mike uses in this tutorial.

So here is how I've been doing it. I'm getting my Shapefile from this website https://www.census.gov/geo/maps-data/data/cbf/cbf_counties.html and going to the Census 2000 tab (because I don't know how else to get only the counties for Missouri from this website) then selecting and downloading Missouri. I then unzip the downloaded file, then move the .shp and .dbf files to a separate folder. Then I run this command to produce the GeoJSON file:

shp2json c029_d00 -o missouri_geo.json

Then this command to make the TopoJSON file

geo2topo missouri_geo.json > missouri_topo.json

When I compare the format of my TopoJSON file to Mike's TopoJSON file, they are kind of similar, but there seems to be a bunch of missing formatting in my TopoJSON file. I understand that since my file is made from the Shapefile of just Missouri, that already there will be missing data, but I thought that my TopoJSON file would have attributes like the 'id' attribute that contains the FIPS codes for the counties, but my file does not have that. I want to figure out the process to convert a Shapefile into a TopoJSON file that can be used with Mike's code from his example, but I can't seem to figure it out.

Note my javascript and html code is exactly the same as Mike's in his example. In my TopoJSON file, I changed the line after "objects":{ to "counties" to match with the line in the javascript code us.objects.counties. When I run my code and inspect it, I do not receive any errors, but nothing shows up. I do not see anything in my browser.

Any help is much appreciated.

Body:
There are a couple potential challenges in replicating this map for a single state and it appears you have run into a few of them. You will need to deviate from the example more than you have.

First, the geographic data your are downloading is composed of latitude longitude pairs - the geographic data the example uses is a pre-projected topojson that is sized to fit in a 960x600 Cartesian plane. You will need to either pre-project your data as well (similar to command line cartography part 1) or project your data on the fly within your block using a geoPath and a geoProjection. Mike does use a geoProjection in his block, a null geoProjection, the default geoProjection for a geoPath. The null projection simply takes coordinates in the json and uses them as svg coordinates with no transform.

Projection issues are probably the most common cause of seeing neither features nor errors. Since you didn't specify a projection, the features are likely rendered off screen. As the continental US sits in the western hemisphere, longitude values are negative - the US will be drawn to the left of the origin, ie off the screen, since you are using a null projection.

The second potential issue for you is that your data has different attributes than the example:

I thought that my TopoJSON file would have attributes like the 'id'
  attribute that contains the FIPS codes for the counties

The feature attributes of your topojson:

"properties":{"AREA":0.140669542963654,
"PERIMETER":1.69104063251173,
"CO29_D00_":2,
"CO29_D00_I":1,
"STATE":"29",
"COUNTY":"045",
"NAME":"Clark",
"LSAD":"06",
"LSAD_TRANS":"County"}}

Are derived from the shapefile:

Since you are using a different source than Mike, the attributes of the data might be different. As the source doesn't have a FIPS ID you cannot make the join between your non-geographic data and your geographic features as in the example. However, there is a not too difficult solution:

Create a FIPS code from the data you do have

From the NOAA (most succinct definition I found):

The first two digits are for the State and the last three identify the County, or county equivalent. So, each State has its own 2-digit number, and each County within the state has its own 3-digit number, which are combined into a 5-digit number to uniquely identify every US county. (source)

You have a number representing state and county - it's a safe bet that this is your FIPS county code when combined. You could combine them in making your geo/topojson, you could create a new property just before drawing the geojson features:

var features = topojson.feature(us, us.objects.counties).features;
features.forEach(function(d) {
   d.FIPS = "" + d.properties.STATE + d.properties.COUNTY;
})

or you could concatenate string and county when filling the feature:

.attr("fill", function(d) { return color(d.rate = unemployment.get(
""+d.properties.STATE+d.properties.COUNTY)); })

Here's what that might look like.


问:
using sort and set() on list values in dictionary
I have a dictionary which has single value as key and a list as the value. I am trying to go through the dictionary values and remove duplicates and sort the lists. Im using the below code to try this.

```<code>def activity_time_from_dict(adict):
    for v in adict.values():
        v = list(set(v))
        v.sort()
</code>```

From printing within the loop it seems to do it correctly, but if I look at the dictionary outside of the loop it has just been sorted and the duplicates remain. I want to replace the original list in the dictionary with the seted and sorted list. What am I doing wrong ?

答:
Use slice assignment

```<code> v[:] = list(set(v))
 # v[:] = set(v)  has the same effect
</code>```

to mutate the object and not just reassign the loop variable. Or more obviously, rebind to the same key:

```<code>for k in adict:
    adict[k] = sorted(set(adict[k]))
</code>```

Body:
I have a dictionary which has single value as key and a list as the value. I am trying to go through the dictionary values and remove duplicates and sort the lists. Im using the below code to try this.

def activity_time_from_dict(adict):
    for v in adict.values():
        v = list(set(v))
        v.sort()

From printing within the loop it seems to do it correctly, but if I look at the dictionary outside of the loop it has just been sorted and the duplicates remain. I want to replace the original list in the dictionary with the seted and sorted list. What am I doing wrong ?

Body:
Use slice assignment

 v[:] = list(set(v))
 # v[:] = set(v)  has the same effect

to mutate the object and not just reassign the loop variable. Or more obviously, rebind to the same key:

for k in adict:
    adict[k] = sorted(set(adict[k]))


问:
Multi-select boxes not search with parent
i'm using select2 in v4.0.3

When I search through the children, for example, "sub category 1", the search appears and your parent "Category 1" is also located above.

https://ibb.co/iNAdLG

But, when I search for "Category 1" it does not show me any of the children. I have reviewed the documentation and several approaches but none has worked for me.

https://ibb.co/eVuSEb

Annex images of reference and code

$("#multisearch").select2({
  language: "es",
  closeOnSelect: false,
  placeholder: "Comienza tu búsqueda",
  data: [{
      id: 0,
      text: 'Linea 1',
      children: [{
          id: 1,
          text: 'San Pablo'
        },
        {
          id: 2,
          text: 'Pajaritos'

        },
        {
          id: 3,
          text: 'Las Rejas'
        },
        {
          id: 4,
          text: 'Ecuador'
        }
      ]
    },
    {
      id: 5,
      text: 'Linea 2',
      children: [{
          id: 6,
          text: 'La Cisterna'
        },
        {
          id: 7,
          text: 'El Parrón'

        },
        {
          id: 8,
          text: 'Lo Ovalle'
        },
        {
          id: 9,
          text: 'Ciudad del niño'
        },
        {
          id: 10,
          text: 'Pajaritos'
        }
      ]
    },
    {
      id: 1,
      text: 'prueba'
    },
  ]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select multiple id="multisearch" style="width:500px">
</select></code>```

I will be attentive, thank you very much

答:
You can achieve this by implementing custom matcher function.

Please check the example below:

$(document).ready(function(){

function customMatcher(params, data) {
        data.parentText = data.parentText || "";
        if ($.trim(params.term) === '') {
            return data;
        }

        if (data.children && data.children.length > 0) {
            var match = $.extend(true, {}, data);
            for (var c = data.children.length - 1; c >= 0; c--) {
                var child = data.children[c];
                child.parentText += data.parentText + " " + data.text;

                var matches = customMatcher(params, child);

                if (matches == null) {
                    match.children.splice(c, 1);
                }
            }

            if (match.children.length > 0) {
                return match;
            }

            return customMatcher(params, match);
        }

        var original = (data.parentText + ' ' + data.text).toUpperCase();
        var term = params.term.toUpperCase();

        if (original.indexOf(term) > -1) {
            return data;
        }

        return null;
    }

$("#multisearch").select2({
  language: "es",
  closeOnSelect: false,
  matcher: customMatcher,
  placeholder: "Comienza tu búsqueda",
  data: [{
      id: 0,
      text: 'Linea 1',
      children: [{
          id: 1,
          text: 'San Pablo'
        },
        {
          id: 2,
          text: 'Pajaritos'

        },
        {
          id: 3,
          text: 'Las Rejas'
        },
        {
          id: 4,
          text: 'Ecuador'
        }
      ]
    },
    {
      id: 5,
      text: 'Linea 2',
      children: [{
          id: 6,
          text: 'La Cisterna'
        },
        {
          id: 7,
          text: 'El Parrón'

        },
        {
          id: 8,
          text: 'Lo Ovalle'
        },
        {
          id: 9,
          text: 'Ciudad del niño'
        },
        {
          id: 10,
          text: 'Pajaritos'
        }
      ]
    },
    {
      id: 1,
      text: 'prueba'
    },
  ]
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select multiple id="multisearch" style="width:500px">
</select></code>```

Body:
i'm using select2 in v4.0.3

When I search through the children, for example, "sub category 1", the search appears and your parent "Category 1" is also located above.

https://ibb.co/iNAdLG

But, when I search for "Category 1" it does not show me any of the children. I have reviewed the documentation and several approaches but none has worked for me.

https://ibb.co/eVuSEb

Annex images of reference and code

$("#multisearch").select2({
  language: "es",
  closeOnSelect: false,
  placeholder: "Comienza tu búsqueda",
  data: [{
      id: 0,
      text: 'Linea 1',
      children: [{
          id: 1,
          text: 'San Pablo'
        },
        {
          id: 2,
          text: 'Pajaritos'

        },
        {
          id: 3,
          text: 'Las Rejas'
        },
        {
          id: 4,
          text: 'Ecuador'
        }
      ]
    },
    {
      id: 5,
      text: 'Linea 2',
      children: [{
          id: 6,
          text: 'La Cisterna'
        },
        {
          id: 7,
          text: 'El Parrón'

        },
        {
          id: 8,
          text: 'Lo Ovalle'
        },
        {
          id: 9,
          text: 'Ciudad del niño'
        },
        {
          id: 10,
          text: 'Pajaritos'
        }
      ]
    },
    {
      id: 1,
      text: 'prueba'
    },
  ]
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

<select multiple id="multisearch" style="width:500px">
</select>

I will be attentive, thank you very much

Body:
You can achieve this by implementing custom matcher function.

Please check the example below:

$(document).ready(function(){

function customMatcher(params, data) {
        data.parentText = data.parentText || "";
        if ($.trim(params.term) === '') {
            return data;
        }

        if (data.children && data.children.length > 0) {
            var match = $.extend(true, {}, data);
            for (var c = data.children.length - 1; c >= 0; c--) {
                var child = data.children[c];
                child.parentText += data.parentText + " " + data.text;

                var matches = customMatcher(params, child);

                if (matches == null) {
                    match.children.splice(c, 1);
                }
            }

            if (match.children.length > 0) {
                return match;
            }

            return customMatcher(params, match);
        }

        var original = (data.parentText + ' ' + data.text).toUpperCase();
        var term = params.term.toUpperCase();

        if (original.indexOf(term) > -1) {
            return data;
        }

        return null;
    }

$("#multisearch").select2({
  language: "es",
  closeOnSelect: false,
  matcher: customMatcher,
  placeholder: "Comienza tu búsqueda",
  data: [{
      id: 0,
      text: 'Linea 1',
      children: [{
          id: 1,
          text: 'San Pablo'
        },
        {
          id: 2,
          text: 'Pajaritos'

        },
        {
          id: 3,
          text: 'Las Rejas'
        },
        {
          id: 4,
          text: 'Ecuador'
        }
      ]
    },
    {
      id: 5,
      text: 'Linea 2',
      children: [{
          id: 6,
          text: 'La Cisterna'
        },
        {
          id: 7,
          text: 'El Parrón'

        },
        {
          id: 8,
          text: 'Lo Ovalle'
        },
        {
          id: 9,
          text: 'Ciudad del niño'
        },
        {
          id: 10,
          text: 'Pajaritos'
        }
      ]
    },
    {
      id: 1,
      text: 'prueba'
    },
  ]
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select multiple id="multisearch" style="width:500px">
</select>


问:
UWP Mapcontrol - Binding to collections of different MapElement and arranging them in layers
I am displaying several different types of MapElements on the UWP MapControl and regularly updating their position, size, etc. as the user works with the map. Currently I do all of this in code. I'd like to find a convenient way of binding multiple different collections of MapElements, as then I'd have less code to maintain. </p>

<p>With Creator's fall update 16299 Microsoft has added the MapElementsLayer class, and It appears to be perfect for the job, but I cannot get it to work.
When I bind it to an ObservableCollection of MapElement3D I don't see any of them appear on the map. What am I doing wrong? </p>

```<code><Maps:MapControl
        x:Name="MainMap"
        MapProjection="Globe"
        ZoomLevel="15.5"

        <Maps:MapElementsLayer x:Name="Cars"  MapElements="{x:Bind _VehicleCollection, Mode=OneWay}"  />

 </Maps:MapControl>
</code>```

答:
I'd like to find a convenient way of binding multiple different collections of MapElements, as then I'd have less code to maintain.

As you mentioned, map layering APIs can help represent a collection of map data to which you can bind data. Unlike the existing MapControl.MapElements API, this can be used to manipulate groups of elements independently as a unit or to designate a joint purpose.

But you need to bind data collection to the map using MapControl.Layers. This is something that you can't do by using the MapElements collection. More details about map layering APIs and how to do please reference Working with layers. For example:

```<code><Maps:MapControl
    x:Name="myMap"
    Layers="{x:Bind ViewModel.LandmarkLayer}"
    MapProjection="Globe"
    MapServiceToken="Your token" />
</code>```

You need to bind layers collection to MapControl.Layers property.

Body:
I am displaying several different types of MapElements on the UWP MapControl and regularly updating their position, size, etc. as the user works with the map. Currently I do all of this in code. I'd like to find a convenient way of binding multiple different collections of MapElements, as then I'd have less code to maintain.

With Creator's fall update 16299 Microsoft has added the MapElementsLayer class, and It appears to be perfect for the job, but I cannot get it to work.
When I bind it to an ObservableCollection of MapElement3D I don't see any of them appear on the map. What am I doing wrong?

<Maps:MapControl
        x:Name="MainMap"
        MapProjection="Globe"
        ZoomLevel="15.5"

        <Maps:MapElementsLayer x:Name="Cars"  MapElements="{x:Bind _VehicleCollection, Mode=OneWay}"  />

 </Maps:MapControl>

Body:
I'd like to find a convenient way of binding multiple different collections of MapElements, as then I'd have less code to maintain.

As you mentioned, map layering APIs can help represent a collection of map data to which you can bind data. Unlike the existing MapControl.MapElements API, this can be used to manipulate groups of elements independently as a unit or to designate a joint purpose.

But you need to bind data collection to the map using MapControl.Layers. This is something that you can't do by using the MapElements collection. More details about map layering APIs and how to do please reference Working with layers. For example:

<Maps:MapControl
    x:Name="myMap"
    Layers="{x:Bind ViewModel.LandmarkLayer}"
    MapProjection="Globe"
    MapServiceToken="Your token" />

You need to bind layers collection to MapControl.Layers property.


问:
Java Socket programming push servlet - Servlet is not getting initialised after deploying it to the server
Any one can help on this?. Locally it is working without any issue. After the application deployment to the server, it is not initialising the push servlet, throwing below exception.

05-Dec-2017 13:26:31.898 SEVERE [http-nio-8080-exec-1]
  org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service()
  for servlet [Push Servlet] in context with path [] threw exception
  java.lang.IllegalStateException: A filter or servlet of the current
  chain does not support asynchronous operations.   at
  org.apache.catalina.connector.Request.startAsync(Request.java:1621)
    at
  org.apache.catalina.connector.RequestFacade.startAsync(RequestFacade.java:1037)

Thanks,

Abees

答:
Download the following jar and add it to the your WEB-INF/lib directory

http://repo1.maven.org/maven2/javax/servlet/jstl/1.2/jstl-1.2.jar

http://repo1.maven.org/maven2/javax/servlet/jsp-api/2.0/jsp-api-2.0.jar

http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/jakarta-taglibs-standard-1.1.2.zip

IF you are using maven make sure you have the dependency for jstl artifact:

```<code><dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>
</code>```

and also restart your server and check again..

Body:
Download the following jar and add it to the your WEB-INF/lib directory

http://repo1.maven.org/maven2/javax/servlet/jstl/1.2/jstl-1.2.jar

http://repo1.maven.org/maven2/javax/servlet/jsp-api/2.0/jsp-api-2.0.jar

http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/jakarta-taglibs-standard-1.1.2.zip

IF you are using maven make sure you have the dependency for jstl artifact:

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

and also restart your server and check again..


问:
How do you create a matrix using the following vectors?
You have the three vectors below. Write R code to create a matrix using these three vectors binding by columns. Submit (1) your R code and (2) the output (print) of the object in the Console window:

here are the three vectors below.

```<code>v1 <-c(100001,
100002,
100003,
100004,
100005,
100006,
100007,
100008,
100009
)

v2 <-c(800.64,
217.53,
74.58,
498.6,
723.11,
69.43,
40.15,
58.61,
364.63
)
v3 <-c(3,
3,
2,
3,
4,
2,
2,
2,
2
)
</code>```

Body:
You have the three vectors below. Write R code to create a matrix using these three vectors binding by columns. Submit (1) your R code and (2) the output (print) of the object in the Console window:

here are the three vectors below.

v1 <-c(100001,
100002,
100003,
100004,
100005,
100006,
100007,
100008,
100009
)

v2 <-c(800.64,
217.53,
74.58,
498.6,
723.11,
69.43,
40.15,
58.61,
364.63
)
v3 <-c(3,
3,
2,
3,
4,
2,
2,
2,
2
)

Body:
Try:

matrix(c(v1,v2,v3), ncol=3)
        [,1]   [,2] [,3]
 [1,] 100001 800.64    3
 [2,] 100002 217.53    3
 [3,] 100003  74.58    2
 [4,] 100004 498.60    3
 [5,] 100005 723.11    4
 [6,] 100006  69.43    2
 [7,] 100007  40.15    2
 [8,] 100008  58.61    2
 [9,] 100009 364.63    2


问:
All support libraries must use the exact same version specification.Found 27.0.1.26.1.0
I am struggling with gradle build error i followed this this and this but none working for me. It was working fine but once i update Exoplayer lib to 2.6 from current but even after reverse i am getting same error. Also when i tried to followed First answer i am getting 7000+ errors in gradle build.

My libraries

答:
the best way is to update all your dependency to use newest support library version.
There is a chance that not all library will be use the same version of sub-component. Try to exclude libraries that use different (older) version of support library using:

```<code> {  exclude group: 'com.android.support'}
</code>```

try this on specific libray :)
P.S. Good lack with architecture components :)

Body:
the best way is to update all your dependency to use newest support library version.
There is a chance that not all library will be use the same version of sub-component. Try to exclude libraries that use different (older) version of support library using:

 {  exclude group: 'com.android.support'}

try this on specific libray :)
P.S. Good lack with architecture components :)


问:
Creating Rainbow Text in Google Docs
```<code>var selectedElements = selection.getSelectedElements();
for (var i = 0; i < selectedElements.length; ++i) {
var selectedElement = selectedElements[i];

// Only modify elements that can be edited as text; skip images and other
// non-text elements.
var text = selectedElement.getElement().editAsText();

// Change the background color of the selected part of the element, or the
// full element if it's completely selected.
if (selectedElement.isPartial()) {
  text.setColor(selectedElement.getStartOffset(),
      selectedElement.getEndOffsetInclusive(), '#69359c');
    }
  }
}
</code>```

The above text takes a selection inside of a Google Doc and changes it to the hex code #69359c (a dark purple). I have searched many websites, many gits, and asked many friends for help with my project.

My end project is this:

Create a menu for Google Docs with my selector (DONE)

Be able to highlight a certain amount of text and change it to an array of colors (ROY G. BIV / the rainbow).

Have the format be only for Google Documents.

If anyone can help me it would be highly appreciated.

答:
I just found this question and am happy to provide some working code from my Rainbow Font Google Docs add-on (Magic Rainbow Unicorns).

The first problem is that you need to set the foreground color on the text, and the second is that the code above only allows for partial paragraph selections.

For whole selections use this code:

```<code>var elementText = element.editAsText();
if (elementText) {
  var paragraph = elementText.getText();
  for (var j = 0; j < paragraph.length; j++) {
    elementText.setForegroundColor(j, j, getNextRainbowColour(...));
  }
}
</code>```

For partial selections, I used this:

```<code>var elementText = element.asText();
var startIndex = element.getStartOffset();
var endIndex = elements.getEndOffsetInclusive();
for (var j = startIndex; j < endIndex+1; j++) {
  elementText.setForegroundColor(j, j, getNextRainbowColour(...));
}
</code>```

Title: Creating Rainbow Text in Google Docs

Body:
var selectedElements = selection.getSelectedElements();
for (var i = 0; i < selectedElements.length; ++i) {
var selectedElement = selectedElements[i];

// Only modify elements that can be edited as text; skip images and other
// non-text elements.
var text = selectedElement.getElement().editAsText();

// Change the background color of the selected part of the element, or the
// full element if it's completely selected.
if (selectedElement.isPartial()) {
  text.setColor(selectedElement.getStartOffset(),
      selectedElement.getEndOffsetInclusive(), '#69359c');
    }
  }
}

The above text takes a selection inside of a Google Doc and changes it to the hex code #69359c (a dark purple). I have searched many websites, many gits, and asked many friends for help with my project.

My end project is this:

Create a menu for Google Docs with my selector (DONE)

Be able to highlight a certain amount of text and change it to an array of colors (ROY G. BIV / the rainbow).

Have the format be only for Google Documents.

If anyone can help me it would be highly appreciated.

Body:
I just found this question and am happy to provide some working code from my Rainbow Font Google Docs add-on (Magic Rainbow Unicorns).

The first problem is that you need to set the foreground color on the text, and the second is that the code above only allows for partial paragraph selections.

For whole selections use this code:

var elementText = element.editAsText();
if (elementText) {
  var paragraph = elementText.getText();
  for (var j = 0; j < paragraph.length; j++) {
    elementText.setForegroundColor(j, j, getNextRainbowColour(...));
  }
}

For partial selections, I used this:

var elementText = element.asText();
var startIndex = element.getStartOffset();
var endIndex = elements.getEndOffsetInclusive();
for (var j = startIndex; j < endIndex+1; j++) {
  elementText.setForegroundColor(j, j, getNextRainbowColour(...));
}


问:
How to make an image of the current rendered map (mapbox-android)?
Is it possible to make a png or data-url of the current view on the map?</p>

答:
There are 2 ways of getting a map bitmap:

from an existing map with MapboxMap#snapshot(SnapshotReadyCallback)

without an existing map using the MapSnapshotter.java class and the related options class.


问:
How to avoid background erasing when drawing lines?
I'm writing a paint app.

When drawing a line in CGContext, the background with the size of the bounding box of the line is always got erased - the underlying lines in that box will be cleared.

How to avoid the background erasing?

答:
[EDIT] Better: see How to draw a line on top of an image when finger moves on iPhone. If your image is added as a background specifically, not directly to the view, it will do what you're looking for.

[original] Keep everything you've drawn already, and redraw it in every call to drawRect via setNeedsDisplay.

Or, set your UIView containing the line to UIColor clearColor.


问:
Mutiprocessing doesn't work in python web-scraping
I have done with web-scraping using beautifulsoup and successfully save the parsed data into csv files but I want to speed up the process so I use multiprocessing. But there is no difference after I apply multiprocessing in the script. Here is my code

```<code>rootPath = '....'
urlp1 = "https://www.proteinatlas.org/"

try:
    df1 = pd.read_csv(rootPath + "cancer_list1_2(1).csv", header=0);
except Exception as e:
    print("File " + f + " doesn't exist")
    print(str(e))
    sys.exit()

cancer_list = df1.as_matrix().tolist()
# [["bcla_gene","beast+cancer"], ...]

URLs = []
for cancer in cancer_list:

    urlp2 = "/pathology/tissue/" + cancer[1]
    f = cancer[0]

    try:
        df1 = pd.read_csv(rootPath + f + ".csv", header=0);
    except Exception as e:
        print("File " + f + " doesn't exist")
        print(str(e))
        sys.exit()
    ... # list of urls

def scrape(url,output_path):
    page = urlopen(URL)
    soup = BeautifulSoup(page, 'html.parser')
    item_text = soup.select('#scatter6001 script')[0].text
    table = soup.find_all('table',{'class':'noborder dark'})
    df1 = pd.read_html(str(table),header = 0)
    df1 = pd.DataFrame(df1[0])
    Number = soup.find('th',text = "Number of samples").find_next_sibling("td").text

...
#function of scraping

if __name__ == "__main__":

    Parallel(n_jobs=-1)(scrape(url,output_path) for url in URLs)
</code>```

Just update the code and the problem now is the CPU utilization can reach 100% only at beginning but soon will drop to 1%. I'm quite confused about that.

答:
Without going to any details in your code: You may benefit from having a look at the joblib module.

Pseudocode:

```<code>import joblib

if __name__ == "__main__":
      URLs = ["URL1", "URL2", "URL2", ...]
      Parallel(n_jobs=-1)(scrape(url,output_path) for url in URLs)
</code>```

Refactoring your code may be necessary because joblib only works if no code runs outside any def: and if __name__ == "__main__":-branch.

n_jobs=-1 will start a number of processes equivalent to the number of cores on your machine. For further details, refer to joblib's documentation.

Using this approach together with selenium/geckodriver, it is possible scrape a pool of 10k URLs in less than an hour depending on your machine (I usually open 40-50 processes on a octacore machine with 64GB ram).

ContentLicense: CC BY-SA 4.0

Body:
I have done with web-scraping using beautifulsoup and successfully save the parsed data into csv files but I want to speed up the process so I use multiprocessing. But there is no difference after I apply multiprocessing in the script. Here is my code

rootPath = '....'
urlp1 = "https://www.proteinatlas.org/"

try:
    df1 = pd.read_csv(rootPath + "cancer_list1_2(1).csv", header=0);
except Exception as e:
    print("File " + f + " doesn't exist")
    print(str(e))
    sys.exit()

cancer_list = df1.as_matrix().tolist()
# [["bcla_gene","beast+cancer"], ...]

URLs = []
for cancer in cancer_list:

    urlp2 = "/pathology/tissue/" + cancer[1]
    f = cancer[0]

    try:
        df1 = pd.read_csv(rootPath + f + ".csv", header=0);
    except Exception as e:
        print("File " + f + " doesn't exist")
        print(str(e))
        sys.exit()
    ... # list of urls

def scrape(url,output_path):
    page = urlopen(URL)
    soup = BeautifulSoup(page, 'html.parser')
    item_text = soup.select('#scatter6001 script')[0].text
    table = soup.find_all('table',{'class':'noborder dark'})
    df1 = pd.read_html(str(table),header = 0)
    df1 = pd.DataFrame(df1[0])
    Number = soup.find('th',text = "Number of samples").find_next_sibling("td").text

...
#function of scraping

if __name__ == "__main__":

    Parallel(n_jobs=-1)(scrape(url,output_path) for url in URLs)

Just update the code and the problem now is the CPU utilization can reach 100% only at beginning but soon will drop to 1%. I'm quite confused about that.

Body:
Without going to any details in your code: You may benefit from having a look at the joblib module.

Pseudocode:

import joblib

if __name__ == "__main__":
      URLs = ["URL1", "URL2", "URL2", ...]
      Parallel(n_jobs=-1)(scrape(url,output_path) for url in URLs)

Refactoring your code may be necessary because joblib only works if no code runs outside any def: and if __name__ == "__main__":-branch.

n_jobs=-1 will start a number of processes equivalent to the number of cores on your machine. For further details, refer to joblib's documentation.

Using this approach together with selenium/geckodriver, it is possible scrape a pool of 10k URLs in less than an hour depending on your machine (I usually open 40-50 processes on a octacore machine with 64GB ram).


问:
Copying a folder to docker container
I was trying to copy a folder from my local host to a docker container in the interactive mode using the following docker command:

docker run -it -v /folder/folder/workspace/folder/folder/*:/tool-1.0/Projects/DemoProject/ --name container imagename

The contents of the folder in the container are getting removed when I run the above command.

Is there any other way to copy the folder into a container?

答:
use docker cp command

make folder as tar and move to running container using below command

docker cp file.tar container_id:/opt/

ref : https://docs.docker.com/engine/reference/commandline/cp/

Title: Copying a folder to docker container


问:
How to clear contents of bootstrap default modal in angular 2
There are some input elements in my modal,when I input contents into it and reopen the modal it doesn't reset it.how can I refresh the modal contents on each time when I open it.

how can i reset my form elements at each time when i reopen the modal.

```<code><li class="top-button"> <a data-toggle="modal" data-target="#signup_modal" class="btn-custom btn" (click)="closemo()">Sign Up</a>

<div class="modal fade" id="signup_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div  class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"    #closeBtnReg><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">Sign Up</h4>
                </div>
                <div class="modal-body">
                    <div class="">
                        <div class="">
                            <div class="">
                                <div class="panel-heading"> </div>
                                <div class="panel-body">
                                    <form (ngSubmit)="register(customerregisterForm)" #customerregisterForm="ngForm" novalidate>
                                        <fieldset>
                                            <div class="form-group">
                                                <input type="text" class="form-control" id="signup_name" placeholder="Name" [(ngModel)]=" signup_name" name="signup_name" minlength="3" maxlength="30" #titlename="ngModel"  required>
                                                <div *ngIf="titlename.errors && (titlename.dirty || titlename.touched)" class="alert alert-danger">
                                                    <div [hidden]="!titlename.errors.required">
                                                        Name is required!
                                                    </div>
                                                    <div [hidden]="!titlename.errors.minlength">
                                                        Name must be at least 3 characters long.
                                                    </div>
                                                    <div [hidden]="!titlename.errors.maxlength">
                                                        Name cannot be more than 30 characters long.
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <input type="email" class="form-control" id="signup_email" placeholder="Email" [(ngModel)]=" signup_email" name="signup_email" #regmail="ngModel"  pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" required>
                                                <div *ngIf="regmail.errors && (regmail.dirty || regmail.touched) " class="alert alert-danger">
                                                    <div [hidden]="!regmail.errors.required">
                                                        Email is required!
                                                    </div>
                                                    <div  *ngIf="regmail.errors && regmail.errors.pattern">
                                                        Invalid Email!
                                                    </div>
                                                </div>
                                            </div>
                                            <input class="btn btn-lg btn-success btn-block" [class.disabled]="!customerregisterForm.form.valid" type="submit" value="Create Account">
                                        </fieldset>
                                    </form>
                                    <hr/>
                                    <ngb-alert *ngIf="logError" type="danger" (close)="closeAlert(alert)" class="ichat-admin-log-error" [dismissible]="false">{{errorMessage}}</ngb-alert>

                                    <!--
                                     <div class="text-center ">
                                        <h4>OR</h4>
                                    </div>
                                    <input class="btn btn-lg btn-facebook btn-block"  value="Sign up via facebook">
                                    -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

答:
In your component, add this:

```<code>register(form: NgForm){
    form.resetForm();
}
</code>```

You just need to reset your form

Body:
There are some input elements in my modal,when I input contents into it and reopen the modal it doesn't reset it.how can I refresh the modal contents on each time when I open it.

how can i reset my form elements at each time when i reopen the modal.

 Sign Up

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"    #closeBtnReg>×</button>

Sign Up

                                    <form (ngSubmit)="register(customerregisterForm)" #customerregisterForm="ngForm" novalidate>
                                        <fieldset>

                                                <input type="text" class="form-control" id="signup_name" placeholder="Name" [(ngModel)]=" signup_name" name="signup_name" minlength="3" maxlength="30" #titlename="ngModel"  required>

                                                        Name is required!

                                                        Name must be at least 3 characters long.

                                                        Name cannot be more than 30 characters long.

                                                <input type="email" class="form-control" id="signup_email" placeholder="Email" [(ngModel)]=" signup_email" name="signup_email" #regmail="ngModel"  pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" required>

                                                        Email is required!

                                                        Invalid Email!

                                            <input class="btn btn-lg btn-success btn-block" [class.disabled]="!customerregisterForm.form.valid" type="submit" value="Create Account">
                                        </fieldset>
                                    </form>

                                    <ngb-alert *ngIf="logError" type="danger" (close)="closeAlert(alert)" class="ichat-admin-log-error" [dismissible]="false">{{errorMessage}}</ngb-alert>

Body:
In your component, add this:

register(form: NgForm){
    form.resetForm();
}

You just need to reset your form


问:
elisp implementation of the "uniq -c" Unix command to count unique lines
If there is a data in region:

```
flower
park
flower
stone
flower
stone
stone
flower
```

M-x some-command should give me in different buffer:

```
4 flower
2 stone
1 park
```

This data can then be sorted by frequency or item.

答:
I suppose there are lots of approaches you could take to this. Here's a fairly simple approach:

(defun uniq-c (beginning end)
  "Like M-| uniq -c"
  (interactive "r")
  (let ((source (current-buffer))
        (dest (generate-new-buffer "*uniq-c*"))
        (case-fold-search nil))
    (set-buffer dest)
    (insert-buffer-substring source beginning end)
    (goto-char (point-min))
    (while (let* ((line (buffer-substring (line-beginning-position)
                                          (line-end-position)))
                  (pattern (concat "^" (regexp-quote line) "$"))
                  (count (count-matches pattern (point) (point-max))))
             (insert (format "%d " count))
             (forward-line 1)
             (flush-lines pattern)
             (not (eobp))))
    (pop-to-buffer dest)))
```

Body:
If there is a data in region:

flower
park
flower
stone
flower
stone
stone
flower

M-x some-command should give me in different buffer:

4 flower
2 stone
1 park

This data can then be sorted by frequency or item.


问:
combining two dictionaries after removing some componetnts
I have two dictionaries as follows.

```<code>  A=  {'photos': {'page': 1,
  'pages': 2,
  'perpage': 250,
  'photo': [{'accuracy': '16',
    'context': 0,
    'datetaken': '2013-05-03 13:47:02',
    'datetakengranularity': '0',
    'datetakenunknown': '0',
    'farm': 5,
    'geo_is_contact': 0,
    'geo_is_family': 0,
    'geo_is_friend': 0,
    'geo_is_public': 1,
    'id': '26970758199',
    'isfamily': 0,
    'isfriend': 0,
    'ispublic': 1,
    'latitude': '5.944650',
    'longitude': '80.459766',
    'owner': '61943224@N04',
    'place_id': 'kLamY9hTU7IVDlGv',
    'secret': '1383a29a3b',
    'server': '4563',
    'title': 'Mirissa - Ask your Local Tour Dog',
    'woeid': '2182931'},
   {'accuracy': '14',
    'context': 0,
    'datetaken': '2017-09-28 18:13:17',
    'datetakengranularity': 0,
    'datetakenunknown': '1',
    'farm': 5,
    'geo_is_contact': 0,
    'geo_is_family': 0,
    'geo_is_friend': 0,
    'geo_is_public': 1,
    'id': '37343882352',
    'isfamily': 0,
    'isfriend': 0,
    'ispublic': 1,
    'latitude': '5.930026',
    'longitude': '80.405502',
    'owner': '7415626@N04',
    'place_id': 'J1bv5NZTU70_mRm8',
    'secret': 'c7135b74d2',
    'server': '4335',
    'title': 'Blue whale tail',
    'woeid': '2179328'}],
  'total': '2'},
 'stat': 'ok'}
</code>```

and the second dictonary  as follows:

```<code>    B={'photos': {'page': 2,
      'pages': 2,
      'perpage': 250,
      'photo': [{'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 12:02:57',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8516011398',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': 'e6c6b8548c',
        'server': '8112',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'},
       {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 11:13:47',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8514896103',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '17df7f97e7',
        'server': '8375',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'}],
  'total': '2'},
 'stat': 'ok'}
</code>```

I want to merge this dictonaries together after removing the

```<code>{'photos': {'page': '',
      'pages': '',
      'perpage': '',
</code>```

and removing the last section of each of A and B dictionaries,

```<code>  'total': ''},
 'stat': ''}
</code>```

sections in both A and B. So my final output should be like this,

```<code>C='photo': [{'accuracy': '16',
        'context': 0,
        'datetaken': '2013-05-03 13:47:02',
        'datetakengranularity': '0',
        'datetakenunknown': '0',
        'farm': 5,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '26970758199',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.944650',
        'longitude': '80.459766',
        'owner': '61943224@N04',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '1383a29a3b',
        'server': '4563',
        'title': 'Mirissa - Ask your Local Tour Dog',
        'woeid': '2182931'},
       {'accuracy': '14',
        'context': 0,
        'datetaken': '2017-09-28 18:13:17',
        'datetakengranularity': 0,
        'datetakenunknown': '1',
        'farm': 5,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '37343882352',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.930026',
        'longitude': '80.405502',
        'owner': '7415626@N04',
        'place_id': 'J1bv5NZTU70_mRm8',
        'secret': 'c7135b74d2',
        'server': '4335',
        'title': 'Blue whale tail',
        'woeid': '2179328'},
       {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 12:02:57',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8516011398',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': 'e6c6b8548c',
        'server': '8112',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'},
        {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 11:13:47',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8514896103',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '17df7f97e7',
        'server': '8375',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'}]
</code>```

I have tried several dictionaries merging methods, and none of those yield results, I'm bit new to python. I would be grateful if someone can help.

答:
Here is solution:-</p>

```<code>def mergedict(A,B):
    r1 = []
    k = {}
    for (k,v), (k2,v2) in zip(A.items(), B.items()):
        if k=='photos':
            r1.append(A[k]['photo'])
        elif k2=='photos':
            r1.append(B[k2]['photo'])
    k['photos']=r1[0]
    return k

C=mergedict(A,B)
print(C)
</code>```

Body:
I have two dictionaries as follows.

  A=  {'photos': {'page': 1,
  'pages': 2,
  'perpage': 250,
  'photo': [{'accuracy': '16',
    'context': 0,
    'datetaken': '2013-05-03 13:47:02',
    'datetakengranularity': '0',
    'datetakenunknown': '0',
    'farm': 5,
    'geo_is_contact': 0,
    'geo_is_family': 0,
    'geo_is_friend': 0,
    'geo_is_public': 1,
    'id': '26970758199',
    'isfamily': 0,
    'isfriend': 0,
    'ispublic': 1,
    'latitude': '5.944650',
    'longitude': '80.459766',
    'owner': '61943224@N04',
    'place_id': 'kLamY9hTU7IVDlGv',
    'secret': '1383a29a3b',
    'server': '4563',
    'title': 'Mirissa - Ask your Local Tour Dog',
    'woeid': '2182931'},
   {'accuracy': '14',
    'context': 0,
    'datetaken': '2017-09-28 18:13:17',
    'datetakengranularity': 0,
    'datetakenunknown': '1',
    'farm': 5,
    'geo_is_contact': 0,
    'geo_is_family': 0,
    'geo_is_friend': 0,
    'geo_is_public': 1,
    'id': '37343882352',
    'isfamily': 0,
    'isfriend': 0,
    'ispublic': 1,
    'latitude': '5.930026',
    'longitude': '80.405502',
    'owner': '7415626@N04',
    'place_id': 'J1bv5NZTU70_mRm8',
    'secret': 'c7135b74d2',
    'server': '4335',
    'title': 'Blue whale tail',
    'woeid': '2179328'}],
  'total': '2'},
 'stat': 'ok'}

and the second dictonary  as follows:

    B={'photos': {'page': 2,
      'pages': 2,
      'perpage': 250,
      'photo': [{'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 12:02:57',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8516011398',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': 'e6c6b8548c',
        'server': '8112',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'},
       {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 11:13:47',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8514896103',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '17df7f97e7',
        'server': '8375',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'}],
  'total': '2'},
 'stat': 'ok'}

I want to merge this dictonaries together after removing the

{'photos': {'page': '',
      'pages': '',
      'perpage': '',

and removing the last section of each of A and B dictionaries,

  'total': ''},
 'stat': ''}

sections in both A and B. So my final output should be like this,

C='photo': [{'accuracy': '16',
        'context': 0,
        'datetaken': '2013-05-03 13:47:02',
        'datetakengranularity': '0',
        'datetakenunknown': '0',
        'farm': 5,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '26970758199',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.944650',
        'longitude': '80.459766',
        'owner': '61943224@N04',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '1383a29a3b',
        'server': '4563',
        'title': 'Mirissa - Ask your Local Tour Dog',
        'woeid': '2182931'},
       {'accuracy': '14',
        'context': 0,
        'datetaken': '2017-09-28 18:13:17',
        'datetakengranularity': 0,
        'datetakenunknown': '1',
        'farm': 5,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '37343882352',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.930026',
        'longitude': '80.405502',
        'owner': '7415626@N04',
        'place_id': 'J1bv5NZTU70_mRm8',
        'secret': 'c7135b74d2',
        'server': '4335',
        'title': 'Blue whale tail',
        'woeid': '2179328'},
       {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 12:02:57',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8516011398',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': 'e6c6b8548c',
        'server': '8112',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'},
        {'accuracy': '12',
        'context': 0,
        'datetaken': '2013-02-19 11:13:47',
        'datetakengranularity': '0',
        'datetakenunknown': 0,
        'farm': 9,
        'geo_is_contact': 0,
        'geo_is_family': 0,
        'geo_is_friend': 0,
        'geo_is_public': 1,
        'id': '8514896103',
        'isfamily': 0,
        'isfriend': 0,
        'ispublic': 1,
        'latitude': '5.935533',
        'longitude': '80.446357',
        'owner': '22857808@N03',
        'place_id': 'kLamY9hTU7IVDlGv',
        'secret': '17df7f97e7',
        'server': '8375',
        'title': 'Whale & Dolphin Watching Mirissa',
        'woeid': '2182931'}]

I have tried several dictionaries merging methods, and none of those yield results, I'm bit new to python. I would be grateful if someone can help.

Body:
Here is solution:-

def mergedict(A,B):
    r1 = []
    k = {}
    for (k,v), (k2,v2) in zip(A.items(), B.items()):
        if k=='photos':
            r1.append(A[k]['photo'])
        elif k2=='photos':
            r1.append(B[k2]['photo'])
    k['photos']=r1[0]
    return k

C=mergedict(A,B)
print(C)