问:
.Net Web API Doesn't Match Route
I am having some trouble understanding how Web API 2 handles routing.

I have created a PostsController that works just fine in terms of the standard actions, GET, POST, etc.

I tried to add a custom route that is a PUT action called Save() that takes a model as an argument.

I added [HttpPut] and [Route("save")] in front of the custom route.   I also modified the WebAPIConfig.cs to handle the pattern api/{controller}/{id}/{action}

However, if I go to http://localhost:58385/api/posts/2/save in Postman (with PUT) I get an error message along the lines of No action was found on the controller 'Posts' that matches the name 'save'.  Essentially a glorified 404.

If i change the route to be [Route("{id}/save")] the resulting error remains.

What am I doing incorrectly?

WebAPIConfig.cs

```<code>config.Routes.MapHttpRoute(
     name: "DefaultApi",
     routeTemplate: "api/{controller}/{id}/{action}",
     defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional, }
            );
</code>```

PostController.cs

```<code>// GET: api/Posts
public IHttpActionResult Get()
{
    PostsStore store = new PostsStore();
    var AsyncResult = store.GetPosts();
    return Ok(AsyncResult);
}

// GET: api/Posts/5
public IHttpActionResult Get(string slug)
{
    PostsStore store = new PostsStore();
    var AsyncResult = store.GetBySlug(slug);
    return Ok(AsyncResult);
}

// POST: api/Posts
public IHttpActionResult Post(Post post)
{
    PostsStore store = new PostsStore();
    ResponseResult AsyncResult = store.Create(post);
    return Ok(AsyncResult);
}

    // PUT: api/Posts/5 DELETED to make sure I wasn't hitting some sort of precedent issue.
    //public IHttpActionResult Put(Post post)
   // {

       //     return Ok();
    //}

[HttpPut]
[Route("save")]
public IHttpActionResult Save(Post post)
{
    PostsStore store = new PostsStore();
    ResponseResult AsyncResponse = store.Save(post);
    return Ok(AsyncResponse);
}
</code>```

答:
If using [Route] attribute then that is attribute routing as apposed to the convention-based routing that you configure. You would need to also enable attribute routing.

```<code>//WebAPIConfig.cs

// enable attribute routing
config.MapHttpAttributeRoutes();

//...add other convention-based routes
</code>```

And also the route template would have to properly set.

```<code>//PostController.cs

[HttpPut]
[Route("api/posts/{id}/save")] // Matches PUT api/posts/2/save
public IHttpActionResult Save(int id, [FromBody]Post post) {
    PostsStore store = new PostsStore();
    ResponseResult AsyncResponse = store.Save(post);
    return Ok(AsyncResponse);
}
</code>```

Reference Attribute Routing in ASP.NET Web API 2

Title: .Net Web API Doesn't Match Route

Body:
I am having some trouble understanding how Web API 2 handles routing.

I have created a PostsController that works just fine in terms of the standard actions, GET, POST, etc.

I tried to add a custom route that is a PUT action called Save() that takes a model as an argument.

I added [HttpPut] and [Route("save")] in front of the custom route.   I also modified the WebAPIConfig.cs to handle the pattern api/{controller}/{id}/{action}

However, if I go to http://localhost:58385/api/posts/2/save in Postman (with PUT) I get an error message along the lines of No action was found on the controller 'Posts' that matches the name 'save'.  Essentially a glorified 404.

If i change the route to be [Route("{id}/save")] the resulting error remains.

What am I doing incorrectly?

WebAPIConfig.cs

config.Routes.MapHttpRoute(
     name: "DefaultApi",
     routeTemplate: "api/{controller}/{id}/{action}",
     defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional, }
            );

PostController.cs

// GET: api/Posts
public IHttpActionResult Get()
{
    PostsStore store = new PostsStore();
    var AsyncResult = store.GetPosts();
    return Ok(AsyncResult);
}

// GET: api/Posts/5
public IHttpActionResult Get(string slug)
{
    PostsStore store = new PostsStore();
    var AsyncResult = store.GetBySlug(slug);
    return Ok(AsyncResult);
}

// POST: api/Posts
public IHttpActionResult Post(Post post)
{
    PostsStore store = new PostsStore();
    ResponseResult AsyncResult = store.Create(post);
    return Ok(AsyncResult);
}

    // PUT: api/Posts/5 DELETED to make sure I wasn't hitting some sort of precedent issue.
    //public IHttpActionResult Put(Post post)
   // {

       //     return Ok();
    //}

[HttpPut]
[Route("save")]
public IHttpActionResult Save(Post post)
{
    PostsStore store = new PostsStore();
    ResponseResult AsyncResponse = store.Save(post);
    return Ok(AsyncResponse);
}

Body:
If using [Route] attribute then that is attribute routing as apposed to the convention-based routing that you configure. You would need to also enable attribute routing.

//WebAPIConfig.cs

// enable attribute routing
config.MapHttpAttributeRoutes();

//...add other convention-based routes

And also the route template would have to properly set.

//PostController.cs

[HttpPut]
[Route("api/posts/{id}/save")] // Matches PUT api/posts/2/save
public IHttpActionResult Save(int id, [FromBody]Post post) {
    PostsStore store = new PostsStore();
    ResponseResult AsyncResponse = store.Save(post);
    return Ok(AsyncResponse);
}

Reference Attribute Routing in ASP.NET Web API 2


来源: stackexchange

问:
Give default value when viewing data on php
i have try to get data with following code

```<code>$result = $viral->getData("SELECT * FROM preview WHERE id=$id");

foreach ($result as $res) {
  $title = $res['title'];
  $promoted = $res['promoted'];
  $photo = $res['file'];
}
</code>```

and i view query result with this code

```<code><p><?php echo $title;?></p>
</code>```

i want when value $title in database is blank it will automatically replace by my default value.

Can i give default value when variable $title is blank ?

答:
You can try</p>

```<code>$title = $res['title'];
if (empty($title){
    $title = "assign default title";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have try to get data with following code

$result = $viral->getData("SELECT * FROM preview WHERE id=$id");

foreach ($result as $res) {
  $title = $res['title'];
  $promoted = $res['promoted'];
  $photo = $res['file'];
}

and i view query result with this code

<?php echo $title;?>

i want when value $title in database is blank it will automatically replace by my default value.

Can i give default value when variable $title is blank ?

Body:
You can try

$title = $res['title'];
if (empty($title){
    $title = "assign default title";
}


问:
How can I set an ImageView's position dynamically in Constraint Layout
I have a dynamically created ImageView in one ConstraintLayout. Once I run the app the ImageView is showing on left top corner because no position is defined for the ImageView.

How can I set the position(let's say CENTER) of the ImageView dynamically?

I have written the below code:

```<code>ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);

ImageView imageView = new ImageView(ChooseOptionsActivity.this);
imageView.setImageResource(R.drawable.redlight);

layout.addView(imageView);

setContentView(layout);
</code>```

Any suggestion is highly appreciated.

答:
You will need to use a ConstraintSet applied to the ImageView to center it. The documentation for ConstraintSet can be found here.

This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout. ConstraintsSet can be created in various ways...

Perhaps the trickiest thing here is how the view is centered. A good description of the centering technique is here.

For your example, the following code will suffice:

```<code>    // Get existing constraints into a ConstraintSet
    ConstraintSet constraints = new ConstraintSet();
    constraints.clone(layout);
    // Define our ImageView and add it to layout
    ImageView imageView = new ImageView(this);
    imageView.setId(View.generateViewId());
    imageView.setImageResource(R.drawable.redlight);
    layout.addView(imageView);
    // Now constrain the ImageView so it is centered on the screen.
    // There is also a "center" method that can be used here.
    constraints.constrainWidth(imageView.getId(), ConstraintSet.WRAP_CONTENT);
    constraints.constrainHeight(imageView.getId(), ConstraintSet.WRAP_CONTENT);
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.LEFT,
            0, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0, 0.5f);
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.TOP,
            0, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0, 0.5f);
    constraints.applyTo(layout);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dynamically created ImageView in one ConstraintLayout. Once I run the app the ImageView is showing on left top corner because no position is defined for the ImageView.

How can I set the position(let's say CENTER) of the ImageView dynamically?

I have written the below code:

ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);

ImageView imageView = new ImageView(ChooseOptionsActivity.this);
imageView.setImageResource(R.drawable.redlight);

layout.addView(imageView);

setContentView(layout);

Any suggestion is highly appreciated.

Body:
You will need to use a ConstraintSet applied to the ImageView to center it. The documentation for ConstraintSet can be found here.

This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout. ConstraintsSet can be created in various ways...

Perhaps the trickiest thing here is how the view is centered. A good description of the centering technique is here.

For your example, the following code will suffice:

    // Get existing constraints into a ConstraintSet
    ConstraintSet constraints = new ConstraintSet();
    constraints.clone(layout);
    // Define our ImageView and add it to layout
    ImageView imageView = new ImageView(this);
    imageView.setId(View.generateViewId());
    imageView.setImageResource(R.drawable.redlight);
    layout.addView(imageView);
    // Now constrain the ImageView so it is centered on the screen.
    // There is also a "center" method that can be used here.
    constraints.constrainWidth(imageView.getId(), ConstraintSet.WRAP_CONTENT);
    constraints.constrainHeight(imageView.getId(), ConstraintSet.WRAP_CONTENT);
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.LEFT,
            0, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0, 0.5f);
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.TOP,
            0, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0, 0.5f);
    constraints.applyTo(layout);


问:
How to overcome the effect of navigation bar
In my application i want to hide the navigation bar when i m going to previous view and i m hiding navigation bar in viewwiilldisaapper method but the effect is remaining mean it gives the white screen at the time of pop..

so can any one tell me the solution for it.

Thanks to all.

答:
you need to hide navigation bar on viewWillAppear of that page by using

```<code>- (void) viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillDisappear:animated];
}
</code>```

if you need to hide navigation bar in certain condition then you need to put proper if else statements, so use this info with your logic according to your condition.

And view is automatic adjusted so no white space you get after pop but you get at time of pop.(no solution for this).

ContentLicense: CC BY-SA 2.5

Body:
you need to hide navigation bar on viewWillAppear of that page by using

- (void) viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillDisappear:animated];
}

if you need to hide navigation bar in certain condition then you need to put proper if else statements, so use this info with your logic according to your condition.

And view is automatic adjusted so no white space you get after pop but you get at time of pop.(no solution for this).


问:
Google Structure Data Breadcrumb Markup
I"m trying to implement a breadcrumb for Google Structure Data and the following is what I trying to build.

Home > Category > Page Name

The problem start when my manager suggest the syntax.

This is what I got suggested by my manager.

```<code><div itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
  <a href="https://www.example.com" itemprop="url">
    <span itemprop="title">Home</span>
  </a> >
</div>

<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
  <a href=" https://www.example.com/blog" itemprop="url">
    <span itemprop="title">Category</span>
  </a> >
</div>

<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
  <a href=" https://www.example.com/blog/can-work-pregnant/" itemprop="url">
    <span itemprop="title">Page Name</span></a>
</div>
</code>```

This is what i think is correct.

```<code><div itemscope itemtype="http://schema.org/BreadcrumbList">
  <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
    <a itemscope itemtype="http://schema.org/Thing" itemprop="item" href="https://example.com/">
        <span itemprop="name">Home</span></a>
        <meta itemprop="position" content="1" />
  </span>
  <span class="seperator">></span>
  <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
    <a itemscope itemtype="http://schema.org/Thing" itemprop="item" href="https://example.com/category">
      <span itemprop="name">Category</span></a>
      <meta itemprop="position" content="2" />
      </span>
      <span class="seperator">›</span>
    <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
    <a itemscope itemtype="http://schema.org/Thing" itemprop="item" href="https://example.com/category/page">
      <span itemprop="name">Page Name</span></a>
      <meta itemprop="position" content="3" />
  </span>
</div>
</code>```

If you try both syntax, you can see the first one creates 3 separate breadcrumbs instead of one with full data in it.

But since this is what suggested by my manager, I do not want to refuse it unless I have the strong reason to do so.

So, what I want to know is the pros and cons of using the first syntax. Please help me. Thanks in advance.

答: Your method is correct. It produces one breadcrumb trail of 3 levels. Your manager is incorrect. Their way made 3 different "trails" of one level each only. It's not a trail if there is only one item.

Title: Google Structure Data Breadcrumb Markup

Body:
I"m trying to implement a breadcrumb for Google Structure Data and the following is what I trying to build.

Home > Category > Page Name

The problem start when my manager suggest the syntax.

This is what I got suggested by my manager.

    Home
   >

    Category
   >

    Page Name

This is what i think is correct.

        Home
        <meta itemprop="position" content="1" />

  >

      Category
      <meta itemprop="position" content="2" />

      ›

      Page Name
      <meta itemprop="position" content="3" />

If you try both syntax, you can see the first one creates 3 separate breadcrumbs instead of one with full data in it.

But since this is what suggested by my manager, I do not want to refuse it unless I have the strong reason to do so.

So, what I want to know is the pros and cons of using the first syntax. Please help me. Thanks in advance.


问:
How to cache page in MVC Core, only in Production environment
Is there an easy way to cache an MVC Core page (View) only when in Production environment?  I tried the code below, but the  tag helper doesn't work since the  ending tag must be within the  tag.

```<code><environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
</environment>
</code>```

Possibly use the enabled attribute for ?

Thanks.

UPDATE:

If you want to cache the entire page, to avoid having a  section as well as one without it (since you still want that content in a Development environment), I would suppose you could put the entire page into a partial view as noted by some.  That would work.  and you would end up with:

```<code><environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
        @Html.Partial("_PartialViewName")
        *last updated  @DateTime.Now.ToLongTimeString()
    </cache>
</environment>
<environment names="Development">
    @Html.Partial("_PartialViewName")
</environment>
</code>```

Seem correct?

答:
You're missing the closing to the cache tag. Try adding </cache> after your cache tag.

Example:

<environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
        @DateTime.Now
    </cache>
</environment>
```

Body:
Is there an easy way to cache an MVC Core page (View) only when in Production environment?  I tried the code below, but the  tag helper doesn't work since the  ending tag must be within the  tag.

<environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
</environment>

Possibly use the enabled attribute for ?

Thanks.

UPDATE:

If you want to cache the entire page, to avoid having a  section as well as one without it (since you still want that content in a Development environment), I would suppose you could put the entire page into a partial view as noted by some.  That would work.  and you would end up with:

<environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
        @Html.Partial("_PartialViewName")
        *last updated  @DateTime.Now.ToLongTimeString()
    </cache>
</environment>
<environment names="Development">
    @Html.Partial("_PartialViewName")
</environment>

Seem correct?


问:
Collapse/Toggle Bootstrap navbar at specific width
I am using Bootstrap navbar and would like it to toggle/collapse at 880px width. I tried adding media queries for 880px width but it did not work. This is my css code:</p>

```<code>@media (min-width: 880px) {
 .navbar-collapse {
  width: auto !important;
  border-top: 0 !important;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
}
.navbar-collapse.collapse {
  display: block !important;
  height: auto !important;
  padding-bottom: 0 !important;
  overflow: visible !important;
 }
.navbar-collapse.in {
  overflow-y: visible;
 }
 .navbar-fixed-top .navbar-collapse,
 .navbar-static-top .navbar-collapse,
 .navbar-fixed-bottom .navbar-collapse {
   padding-right: 0 !important;
   padding-left: 0 !important;
 }
 .container > .navbar-header,
 .container-fluid > .navbar-header,
 .container > .navbar-collapse,
 .container-fluid > .navbar-collapse {
   margin-right: 0 !important;
   margin-left: 0 !important;
 }
}
</code>```

答:
I found this as I was looking for the same solution.

UPDATE for Bootstrap 3.1

```<code>@media (max-width: 1200px) {
.navbar-header {
    float: none;
}
.navbar-left,.navbar-right {
    float: none !important;
}
.navbar-toggle {
    display: block;
}
.navbar-collapse {
    border-top: 1px solid transparent;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
}
.navbar-fixed-top {
    top: 0;
    border-width: 0 0 1px;
}
.navbar-collapse.collapse {
    display: none!important;
}
.navbar-nav {
    float: none!important;
    margin-top: 7.5px;
}
.navbar-nav>li {
    float: none;
}
.navbar-nav>li>a {
    padding-top: 10px;
    padding-bottom: 10px;
}
.collapse.in{
    display:block !important;
    }
}
</code>```

This customization works well. Instead of 1200px write your custom size (880px). If you would like to read the whole text here is the link
https://coderwall.com/p/wpjw4w/change-the-bootstrap-navbar-breakpoint

Body:
I am using Bootstrap navbar and would like it to toggle/collapse at 880px width. I tried adding media queries for 880px width but it did not work. This is my css code:

@media (min-width: 880px) {
 .navbar-collapse {
  width: auto !important;
  border-top: 0 !important;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
}
.navbar-collapse.collapse {
  display: block !important;
  height: auto !important;
  padding-bottom: 0 !important;
  overflow: visible !important;
 }
.navbar-collapse.in {
  overflow-y: visible;
 }
 .navbar-fixed-top .navbar-collapse,
 .navbar-static-top .navbar-collapse,
 .navbar-fixed-bottom .navbar-collapse {
   padding-right: 0 !important;
   padding-left: 0 !important;
 }
 .container > .navbar-header,
 .container-fluid > .navbar-header,
 .container > .navbar-collapse,
 .container-fluid > .navbar-collapse {
   margin-right: 0 !important;
   margin-left: 0 !important;
 }
}

Body:
I found this as I was looking for the same solution.

UPDATE for Bootstrap 3.1

@media (max-width: 1200px) {
.navbar-header {
    float: none;
}
.navbar-left,.navbar-right {
    float: none !important;
}
.navbar-toggle {
    display: block;
}
.navbar-collapse {
    border-top: 1px solid transparent;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
}
.navbar-fixed-top {
    top: 0;
    border-width: 0 0 1px;
}
.navbar-collapse.collapse {
    display: none!important;
}
.navbar-nav {
    float: none!important;
    margin-top: 7.5px;
}
.navbar-nav>li {
    float: none;
}
.navbar-nav>li>a {
    padding-top: 10px;
    padding-bottom: 10px;
}
.collapse.in{
    display:block !important;
    }
}

This customization works well. Instead of 1200px write your custom size (880px). If you would like to read the whole text here is the link
https://coderwall.com/p/wpjw4w/change-the-bootstrap-navbar-breakpoint


问:
Lookup value in one dataframe and paste it into another dataframe
I have two dataframes in Python one big (car listings), one small (car base configuration prices). The small one looks like this:

```<code>      Make  Model               MSRP
0   Acura   ILX                27990
1   Acura   MDX                43015
2   Acura   MDX Sport Hybrid    51960
3   Acura   NSX                156000
4   Acura   RDX                 35670
5   Acura   RLX                54450
6   Acura   TLX                31695
7   Alfa Romeo  4C             55900
8   Alfa Romeo  Giulia         37995
…   …          … .               …
391 Toyota  Yaris              14895
392 Toyota  Yaris iA           15950
393 Volkswagen  Atlas          33500
394 Volkswagen  Beetle         19795
395 Volkswagen  CC             34475
396 Volkswagen  GTI            24995
397 Volkswagen  Golf           19575
398 Volkswagen  Golf Alltrack  25850
399 Volkswagen  Golf R         37895
400 Volkswagen  Golf SportWagen 21580
401 Volkswagen  Jetta           17680
402 Volkswagen  Passat          22440
403 Volkswagen  Tiguan          24890
404 Volkswagen  Touareg         42705
405 Volkswagen  e-Golf          28995
406 Volvo        S60            33950
</code>```

Now I want to paste the values from the MSRP column (far right column) based on matching the Make and Model columns into the big dataframe (car listings) that looks like the following:

```<code>    makeName    modelName   trimName    carYear mileage
0   BMW            X5         sDrive35i   2017     0
1   BMW            X5         sDrive35i   2017     3
2   BMW            X5         sDrive35i   2017     0
3   Audi           A4         Premium Plus2017     0
4   Kia          Optima       LX          2016    10
5   Kia          Optima       SX Turbo    2017    15
6   Kia          Optima       EX          2016    425
7   Rolls-Royce   Ghost       Series II   2017    15
…    …              …          …            …      …
</code>```

In the end I would like to have the following:

```<code>    makeName    modelName   trimName    carYear mileage  MSRP
0   BMW            X5         sDrive35i   2017     0     value from the other table
1   BMW            X5         sDrive35i   2017     3     value from the other table
2   BMW            X5         sDrive35i   2017     0     value from the other table
3   Audi           A4         Premium Plus2017     0     value from the other table
4   Kia          Optima       LX          2016    10     value from the other table
5   Kia          Optima       SX Turbo    2017    15     value from the other table
6   Kia          Optima       EX          2016    425    value from the other table
7   Rolls-Royce   Ghost       Series II   2017    15     value from the other table
…    …              …          …            …      …
</code>```

I read the documentation regarding pd.concat, merge and join but I am not making any progress.

Can you guys help?

Thanks!

答:
You can use merge to join the two dataframes together.

```<code>car_base.merge(car_listings, left_on=['makeName','modelName'], right_on=['Make','Model'])
</code>```

Body:
I have two dataframes in Python one big (car listings), one small (car base configuration prices). The small one looks like this:

      Make  Model               MSRP
0   Acura   ILX                27990
1   Acura   MDX                43015
2   Acura   MDX Sport Hybrid    51960
3   Acura   NSX                156000
4   Acura   RDX                 35670
5   Acura   RLX                54450
6   Acura   TLX                31695
7   Alfa Romeo  4C             55900
8   Alfa Romeo  Giulia         37995
…   …          … .               …
391 Toyota  Yaris              14895
392 Toyota  Yaris iA           15950
393 Volkswagen  Atlas          33500
394 Volkswagen  Beetle         19795
395 Volkswagen  CC             34475
396 Volkswagen  GTI            24995
397 Volkswagen  Golf           19575
398 Volkswagen  Golf Alltrack  25850
399 Volkswagen  Golf R         37895
400 Volkswagen  Golf SportWagen 21580
401 Volkswagen  Jetta           17680
402 Volkswagen  Passat          22440
403 Volkswagen  Tiguan          24890
404 Volkswagen  Touareg         42705
405 Volkswagen  e-Golf          28995
406 Volvo        S60            33950

Now I want to paste the values from the MSRP column (far right column) based on matching the Make and Model columns into the big dataframe (car listings) that looks like the following:

    makeName    modelName   trimName    carYear mileage
0   BMW            X5         sDrive35i   2017     0
1   BMW            X5         sDrive35i   2017     3
2   BMW            X5         sDrive35i   2017     0
3   Audi           A4         Premium Plus2017     0
4   Kia          Optima       LX          2016    10
5   Kia          Optima       SX Turbo    2017    15
6   Kia          Optima       EX          2016    425
7   Rolls-Royce   Ghost       Series II   2017    15
…    …              …          …            …      …

In the end I would like to have the following:

    makeName    modelName   trimName    carYear mileage  MSRP
0   BMW            X5         sDrive35i   2017     0     value from the other table
1   BMW            X5         sDrive35i   2017     3     value from the other table
2   BMW            X5         sDrive35i   2017     0     value from the other table
3   Audi           A4         Premium Plus2017     0     value from the other table
4   Kia          Optima       LX          2016    10     value from the other table
5   Kia          Optima       SX Turbo    2017    15     value from the other table
6   Kia          Optima       EX          2016    425    value from the other table
7   Rolls-Royce   Ghost       Series II   2017    15     value from the other table
…    …              …          …            …      …

I read the documentation regarding pd.concat, merge and join but I am not making any progress.

Can you guys help?

Thanks!

Body:
You can use merge to join the two dataframes together.

car_base.merge(car_listings, left_on=['makeName','modelName'], right_on=['Make','Model'])


问:
unable to register node to hub in selenium
My hub is working successfully and running

```<code>    java -jar selenium-server-standalone-2.53.0.jar -role hub -port 5555
</code>```

my node command

```<code>  java -jar selenium-server-standalone-2.53.0.jar -role webdriver –hub http://localhost:5555/gridhost/register -port 7621
</code>```

but unable to  register my  node forbidden + for + proxy the hub is down or not responding

答:
Try another port:

java -jar selenium-server-standalone-2.53.0.jar -role hub -port 4444

then

java -jar selenium-server-standalone-2.53.0.jar -role webdriver –hub
  http://localhost:4444/gridhost/register -port 7621

It work for me

Body:
My hub is working successfully and running

    java -jar selenium-server-standalone-2.53.0.jar -role hub -port 5555

my node command

  java -jar selenium-server-standalone-2.53.0.jar -role webdriver –hub http://localhost:5555/gridhost/register -port 7621

but unable to  register my  node forbidden + for + proxy the hub is down or not responding


问:
JQuery bug, slidetoggle() function stacks
I have a weird problem with the slideToggle() jQuery function. I don't know what I'm breaking (nor repairing), but sometimes on hover it displays the divs that are normally hidden and sometimes stacks up so that the whole div gets bigger and bigger. I was able to copy the previous jQuery code before and repair it, but now it does nothing. I have a few jQuery codes embedded in my divs so that few of them stay open on hover.

The code looks like that:

```<code>$("#colorstoggle").hover(function(e) {
    $("#red").stop(true, false).slideToggle(200);
    $("#yellow").stop(true, false).slideToggle(200);
    $("#blue").stop(true, false).slideToggle(200);
    $("#green").stop(true, false).slideToggle(200);
    $("#purple").stop(true, false).slideToggle(200);
})

$("#red").hover(function(e) {
    $("#red").stop(true, false).slideToggle();
    $("#yellow").stop(true, false).slideToggle();
    $("#blue").stop(true, false).slideToggle();
    $("#green").stop(true, false).slideToggle();
    $("#purple").stop(true, false).slideToggle();
})
</code>```

And so on...

The html is a list:

```<code><ul class="navigation">
    <li class="nav-item" id="str1but">Podsumowanie</li>
    <li class="nav-item" id="str2but">Dane</li>
    <li class="nav-item" id="str3but">Wykres</li>
    <li class="nav-item" id="str4but">Autorzy</li>
    <li class="nav-item" id="colorstoggle">
    Kolor:</li>
    <li class="nav-item" id="yellow" style="color:yellow">kolor żółty</li>
    <li class="nav-item" id="blue" style="color:blue">kolor niebieski</li>
    <li class="nav-item" id="red" style="color:red">kolor czerwony</li>
    <li class="nav-item" id="purple" style="color:purple">kolor fioletowy</li>
    <li class="nav-item" id="green" style="color:green">kolor zielony</li>
</ul>
</code>```

And the nav-item class is:

```<code>.nav-item {
    width: 200px;
    border-top: 1px solid #111;
    border-bottom: 1px solid #111;
    display: block;
    padding: 0.7em;
    color: white;
    font-size: 1.2em;
    text-decoration: none;
}
</code>```

答:
Here's a Fiddle of your code running, with the background of the ul showing to demonstrate the expanding div.

It's normal that the parent element expands, as by default, HTML block level elements will expand to accommodate the elements within. In this case, the li's are expanding/contracting, so the ul expands/contracts with it.

The code

It's hard to offer specific help, as it's not clear what you are trying to achieve with your code. There are a few things you might consider though:

It looks like you are potentially complicating things by offering 2 controls to do the same thing (slideToggle the same set of elements) and one control (#red) is a target element of the first (#colorstoggle).

It also looks like you are referencing the colour li items as children of #colorstoggle, so you could consider using a nested list to contain these elements separately and reduce confusion. Here's a demo.

You can also cull the amount of repeated code used by grouping your jQuery selectors.

Using multiple selectors in jQuery

```<code>$("#colorstoggle").hover(function(e) {
    $("#red").stop(true, false).slideToggle(200);
    $("#yellow").stop(true, false).slideToggle(200);
    $("#blue").stop(true, false).slideToggle(200);
    $("#green").stop(true, false).slideToggle(200);
    $("#purple").stop(true, false).slideToggle(200);
})
</code>```

Can be reduced into:

```<code>$("#colorstoggle").hover(function(e) {
  $("#red, #yellow, #blue, #green, #purple").stop(true, false).slideToggle(200);
})
</code>```

Body:
I have a weird problem with the slideToggle() jQuery function. I don't know what I'm breaking (nor repairing), but sometimes on hover it displays the divs that are normally hidden and sometimes stacks up so that the whole div gets bigger and bigger. I was able to copy the previous jQuery code before and repair it, but now it does nothing. I have a few jQuery codes embedded in my divs so that few of them stay open on hover.

The code looks like that:

$("#colorstoggle").hover(function(e) {
    $("#red").stop(true, false).slideToggle(200);
    $("#yellow").stop(true, false).slideToggle(200);
    $("#blue").stop(true, false).slideToggle(200);
    $("#green").stop(true, false).slideToggle(200);
    $("#purple").stop(true, false).slideToggle(200);
})

$("#red").hover(function(e) {
    $("#red").stop(true, false).slideToggle();
    $("#yellow").stop(true, false).slideToggle();
    $("#blue").stop(true, false).slideToggle();
    $("#green").stop(true, false).slideToggle();
    $("#purple").stop(true, false).slideToggle();
})

And so on...

The html is a list:

Podsumowanie

Dane

Wykres

Autorzy

    Kolor:

kolor żółty

kolor niebieski

kolor czerwony

kolor fioletowy

kolor zielony

And the nav-item class is:

.nav-item {
    width: 200px;
    border-top: 1px solid #111;
    border-bottom: 1px solid #111;
    display: block;
    padding: 0.7em;
    color: white;
    font-size: 1.2em;
    text-decoration: none;
}

Body:
Here's a Fiddle of your code running, with the background of the ul showing to demonstrate the expanding div.

It's normal that the parent element expands, as by default, HTML block level elements will expand to accommodate the elements within. In this case, the li's are expanding/contracting, so the ul expands/contracts with it.

The code

It's hard to offer specific help, as it's not clear what you are trying to achieve with your code. There are a few things you might consider though:

It looks like you are potentially complicating things by offering 2 controls to do the same thing (slideToggle the same set of elements) and one control (#red) is a target element of the first (#colorstoggle).

It also looks like you are referencing the colour li items as children of #colorstoggle, so you could consider using a nested list to contain these elements separately and reduce confusion. Here's a demo.

You can also cull the amount of repeated code used by grouping your jQuery selectors.

Using multiple selectors in jQuery

$("#colorstoggle").hover(function(e) {
    $("#red").stop(true, false).slideToggle(200);
    $("#yellow").stop(true, false).slideToggle(200);
    $("#blue").stop(true, false).slideToggle(200);
    $("#green").stop(true, false).slideToggle(200);
    $("#purple").stop(true, false).slideToggle(200);
})

Can be reduced into:

$("#colorstoggle").hover(function(e) {
  $("#red, #yellow, #blue, #green, #purple").stop(true, false).slideToggle(200);
})


问:
How can I Convert Calendar.toString() into date using SimpleDateFormat.parse()?
I'm developing an Android app that uses a database, every time that the user insert a new register the current data and time is save in the db using

```<code>Calendar cal = Calendar.getInstance();
</code>```

So, When I retrieve the data from the db, got a String like this:

java.util.GregorianCalendar[time=1496007575129,areFieldsSet=true,lenient=true,zone=America/Mexico_City,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=4,WEEK_OF_YEAR=22,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=148,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=39,SECOND=35,MILLISECOND=129,ZONE_OFFSET=-21600000,DST_OFFSET=3600000]

The problem comes when I try convert that String using SimpleDateFormat.parse to display it in a RecyclerView, I get always the same date: 09/04/2017.

This is the code in my RecViewAdapter.java:

```<code>@Override
public void onBindViewHolder(ViewHolder holder,int position){
    items.moveToPosition(position);

    String s,d,p,f;

    s = items.getString(ConsultaTomas.SISTOLICA);
    holder.systolica.setText(s);

    d = items.getString(ConsultaTomas.DIASTOLICA);
    holder.diastolica.setText(d);

    p = items.getString(ConsultaTomas.PULSO);
    holder.pulso.setText(p);

    f = items.getString(ConsultaTomas.FECHA);
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    try {
        holder.fecha.setText(sdf.format(sdf.parse(f)));

    }catch (ParseException e){
        Log.d("PARSINGFECHA","Error al parcear fecha");
    }

}
</code>```

The other data is showed correctly in the RecView and the Calendar String are all diferent, so there is not the same date/hour in these strings. So, the question is:

How can I Convert Calendar.toString() into date using SimpleDateFormat.parse()?

This is the result running the app in a real device:

答:
You need to modify the way you store the Calendar, call getTime() and format it as desired to begin with. For example,

```<code>Calendar cal = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(sdf.format(cal.getTime()));
</code>```

Body:
I'm developing an Android app that uses a database, every time that the user insert a new register the current data and time is save in the db using

Calendar cal = Calendar.getInstance();

So, When I retrieve the data from the db, got a String like this:

java.util.GregorianCalendar[time=1496007575129,areFieldsSet=true,lenient=true,zone=America/Mexico_City,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=4,WEEK_OF_YEAR=22,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=148,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=39,SECOND=35,MILLISECOND=129,ZONE_OFFSET=-21600000,DST_OFFSET=3600000]

The problem comes when I try convert that String using SimpleDateFormat.parse to display it in a RecyclerView, I get always the same date: 09/04/2017.

This is the code in my RecViewAdapter.java:

@Override
public void onBindViewHolder(ViewHolder holder,int position){
    items.moveToPosition(position);

    String s,d,p,f;

    s = items.getString(ConsultaTomas.SISTOLICA);
    holder.systolica.setText(s);

    d = items.getString(ConsultaTomas.DIASTOLICA);
    holder.diastolica.setText(d);

    p = items.getString(ConsultaTomas.PULSO);
    holder.pulso.setText(p);

    f = items.getString(ConsultaTomas.FECHA);
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    try {
        holder.fecha.setText(sdf.format(sdf.parse(f)));

    }catch (ParseException e){
        Log.d("PARSINGFECHA","Error al parcear fecha");
    }

}

The other data is showed correctly in the RecView and the Calendar String are all diferent, so there is not the same date/hour in these strings. So, the question is:

How can I Convert Calendar.toString() into date using SimpleDateFormat.parse()?

This is the result running the app in a real device:

Body:
You need to modify the way you store the Calendar, call getTime() and format it as desired to begin with. For example,

Calendar cal = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(sdf.format(cal.getTime()));


问:
Why is my navbar and carousel not working?
This is my text for the HTML currently. I am having difficulties with the carousel and can't get it to display images properly. On top of the carousel not working, I have an issue with my nav bar background color. It won't stay at 100% width. Going back to the carousel, When I try live view and click on arrows to go to next or prev, resets it's placement behind the NavBar.

```<code><html>
    <head>
        <title>Funky Munky Arcade</title>

        <meta name="viewport" content="width=device-width, initional-scale=1">

        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <link rel="stylesheet" type="text/css" href="style.css">

    </head>

    <body>

        <nav class="navbar navbar-default navbar-fixed-top">

            <div class="container nav-container">

                    <ul class="nav nav-justified">
                        <li><a href="#">Parties</a></li>
                    </ul>

                <div class="navbar-header">

                    <a href="/index.html" class="navbar-left"><img src="http://i.imgur.com/UXms4Eq.png" class="logo"></a>

                </div>

                    <ul class="nav nav-justified">
                        <li><a href="#">Contact</a></li>
                    </ul>

            </div>

        </nav>

        <!-- Beginning of Carousel -->

        <div class="carousel slide" id="bannerslides" data-ride="carousel">

            <!-- Indicators -->

            <ol class="carousel-indicators">

                <li data-target="#bannerslides" data-slide-to="0" class="active">
                </li>

                <li data-target="#bannerslides" data-slide-to="1">
                </li>

                <li data-target="#bannerslides" data-slide-to="2">
                </li>

                <li data-target="#bannerslides" data-slide-to="3">
                </li>

            </ol>

            <!-- End of Indicators -->

            <!-- Wrapper for Slides -->

            <div class="carousel-inner">

                <div class="item active">

                    <img src="https://db.tt/W08hePZ53h">

                </div>

                <div class="item">

                    <img src="http://i.imgur.com/t0Y4JDI.png">

                </div>

                <div class="item">

                    <img src="http://i.imgur.com/zaUETSd.png">

                </div>

                <div class="item">

                    <img src="http://i.imgur.com/LRATkRS.png">

                </div>

            </div>

            <!-- End of Wrapper -->

            <!-- Beginning of Carousel Controls -->

            <a class="left carousel-control" href="#bannerslides" data-slide="prev">
                <span class="glyphicon glyphicon-chevron-left"></span>
            </a>

            <a class="right carousel-control" href="#bannerslides" data-slide="next">
                <span class="glyphicon glyphicon-chevron-right"></span>
            </a>

            <!-- End of Carousel Controls -->

        </div>

        <!-- End of Carousel -->
</code>```

Here is my CSS:

```<code>.nav-container {
display: flex;
align-items: center;
background-color: red;
width: 100%;
}
.head {
text-align: center;
}
.intro{
font-size: 48px;
text-align: center;
}
.jumbotron{
background-color: white;
font-size: 24px;
}
.navbar-fixed-top{
background-color: red;
border: 0px;
}
.logo{
background-color: white;
border-radius: 50%;
}
.carousel{
margin-top: 150px;
}
</code>```

答:
You need add file javascript of bootstrapp

Tip: Plugins can be included individually (using Bootstrap's individual "carousel.js" file), or all at once (using "bootstrap.js" or "bootstrap.min.js").
  ref here

Body:
This is my text for the HTML currently. I am having difficulties with the carousel and can't get it to display images properly. On top of the carousel not working, I have an issue with my nav bar background color. It won't stay at 100% width. Going back to the carousel, When I try live view and click on arrows to go to next or prev, resets it's placement behind the NavBar.

        <title>Funky Munky Arcade</title>

        <meta name="viewport" content="width=device-width, initional-scale=1">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <link rel="stylesheet" type="text/css" href="style.css">

Parties

Contact

Here is my CSS:

.nav-container {
display: flex;
align-items: center;
background-color: red;
width: 100%;
}
.head {
text-align: center;
}
.intro{
font-size: 48px;
text-align: center;
}
.jumbotron{
background-color: white;
font-size: 24px;
}
.navbar-fixed-top{
background-color: red;
border: 0px;
}
.logo{
background-color: white;
border-radius: 50%;
}
.carousel{
margin-top: 150px;
}


问:
Read content of RAR file into memory in Python
I'm looking for a way to read specific files from a rar archive into memory.  Specifically they are a collection of numbered image files (I'm writing a comic reader).  While I can simply unrar these files and load them as needed (deleting them when done), I'd prefer to avoid that if possible.

That all said, I'd prefer a solution that's cross platform (Windows/Linux) if possible, but Linux is a must.  Just as importantly, if you're going to point out a library to handle this for me, please understand that it must be free (as in beer) or OSS.

答:
It seems like the limitation that rarsoft imposes on derivative works is that you may not use the unrar source code to create a variation of the RAR COMPRESSION algorithm.  From the context, it would appear that it's specifically allowing folks to use his code (modified or not) to decompress files, but you cannot use them if you intend to write your own compression code.  Here is a direct quote from the license.txt file I just downloaded:

The UnRAR sources may be used in any software to handle RAR
  archives without limitations free of charge, but cannot be used
  to re-create the RAR compression algorithm, which is proprietary.
  Distribution of modified UnRAR sources in separate form or as a
  part of other software is permitted, provided that it is clearly
  stated in the documentation and source comments that the code may
  not be used to develop a RAR (WinRAR) compatible archiver.

Seeing as everyone seemed to just want something that would allow them to write a comic viewer capable of handling reading images from CBR (rar) files, I don't see why people think there's anything keeping them from using the provided source code.


问:
How to download image asynchronously using cache and display in tableviewcell in objective-C?
I am trying to download image asynchronously using cache and display in tableviewcell in objective-C. Image is coming from URL. I have written API calling using NSSession and doing background calling using GCD but in this case image is downloading again again while scrolling. I want to image download only once.

```<code> //------------ using GCD ---------
        if(![imageUrlString isKindOfClass:[NSNull class]]){

                dispatch_async(dispatch_get_global_queue(0,0), ^{
                  NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
                    if ( data == nil )
                        return;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // WARNING: is the cell still using the same data by this point??
                        cell.imageView.image = [UIImage imageWithData: data];
                    });
                });
        }
        //------------ using GCD -----
</code>```

For same cashing is only way? if yes please suggest how can i achieve this.

答:
In development we don't take hassle if we have proper tools and library.Because we have to spend more time in this regard.

SDWebimage is a great library to fulfill your requirement. You don't have to think about all cases. It's already been done for you.

As an example:

```<code>imageView.sd_setImage(with: URL(string: "your domain name"), placeholderImage: UIImage(named: "placeholder.png"))
</code>```

You just have to write this line in cellForRowAtIndexPath. :)
There are also lots of features in this library.
Happy coding.

Body:
I am trying to download image asynchronously using cache and display in tableviewcell in objective-C. Image is coming from URL. I have written API calling using NSSession and doing background calling using GCD but in this case image is downloading again again while scrolling. I want to image download only once.

 //------------ using GCD ---------
        if(![imageUrlString isKindOfClass:[NSNull class]]){

                dispatch_async(dispatch_get_global_queue(0,0), ^{
                  NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
                    if ( data == nil )
                        return;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // WARNING: is the cell still using the same data by this point??
                        cell.imageView.image = [UIImage imageWithData: data];
                    });
                });
        }
        //------------ using GCD -----

For same cashing is only way? if yes please suggest how can i achieve this.

Body:
In development we don't take hassle if we have proper tools and library.Because we have to spend more time in this regard.

SDWebimage is a great library to fulfill your requirement. You don't have to think about all cases. It's already been done for you.

As an example:

imageView.sd_setImage(with: URL(string: "your domain name"), placeholderImage: UIImage(named: "placeholder.png"))

You just have to write this line in cellForRowAtIndexPath. :)
There are also lots of features in this library.
Happy coding.


问:
How can I convert a 2D array to a 2D list with Streams?
I've tried this StackOverflow answer's code, but I get the error Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>):

```<code>//data is int[][]
Arrays.stream(data)
    .map(i -> Arrays.stream(i)
        .collect(Collectors.toList()))
            .collect(Collectors.toList());
</code>```

答:
Try StreamEx

```<code>StreamEx.of(data).map(a -> IntStreamEx.of(a).boxed().toList()).toList();
</code>```

Or abacus-common, simple and most efficient:

```<code>Stream.of(data).map(a -> IntList.of(a).boxed()).toList();

// Or:
Seq.of(data).map(a -> IntList.of(a).boxed());
</code>```

All of them are null safety. An empty list is returned if data is null

Body:
I've tried this StackOverflow answer's code, but I get the error Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>):

//data is int[][]
Arrays.stream(data)
    .map(i -> Arrays.stream(i)
        .collect(Collectors.toList()))
            .collect(Collectors.toList());

Body:
Try StreamEx

StreamEx.of(data).map(a -> IntStreamEx.of(a).boxed().toList()).toList();

Or abacus-common, simple and most efficient:

Stream.of(data).map(a -> IntList.of(a).boxed()).toList();

// Or:
Seq.of(data).map(a -> IntList.of(a).boxed());

All of them are null safety. An empty list is returned if data is null


问:
perl load json from file and loop
I've got a file like this:

```<code>{
    "dev":
    {
        "data": "1"
    },
    "stg":
    {
        "data": "1"
    },
    "pre":
    {
        "data": "1"
    },
    "prod":
    {
        "data": "1"
    },
}
</code>```

I load the json like this:

```<code>open(FH,"<",$file) or die "environments.json file doesn't exists!\n";
my $data = <FH>;

my $ret = JSON::decode_json( $data );
</code>```

It loads properly, I can do:

```<code>print "Dumper: " .  Dumper($ret) . "\n";
</code>```

But when I try to loop through it with:

```<code>foreach my $env( @$ret )
{
    print "Environment: " . $env->{"data"} . "\n";
}
</code>```

I get:

```<code>Not an ARRAY reference at ./launcher.pl line 20, <FH> line 1.
</code>```

On the foreach my $env( @$ret ) line
Help is appreciated!

Thanks!

David

答:
There's no array in that JSON. </p>

```<code>for my $env_name (keys(%$ret)) {
   my $env = $ret->{$env_name};

   ... $env->{data} ...

}
</code>```

Title: perl load json from file and loop

Body:
I've got a file like this:

{
    "dev":
    {
        "data": "1"
    },
    "stg":
    {
        "data": "1"
    },
    "pre":
    {
        "data": "1"
    },
    "prod":
    {
        "data": "1"
    },
}

I load the json like this:

open(FH,"<",$file) or die "environments.json file doesn't exists!\n";
my $data = <FH>;

my $ret = JSON::decode_json( $data );

It loads properly, I can do:

print "Dumper: " .  Dumper($ret) . "\n";

But when I try to loop through it with:

foreach my $env( @$ret )
{
    print "Environment: " . $env->{"data"} . "\n";
}

I get:

Not an ARRAY reference at ./launcher.pl line 20, <FH> line 1.

On the foreach my $env( @$ret ) line
Help is appreciated!

Thanks!

David

Body:
There's no array in that JSON.

for my $env_name (keys(%$ret)) {
   my $env = $ret->{$env_name};

   ... $env->{data} ...

}


问:
how do i extract date from string using php
I need to extract the date from a string, below is my code and the string.

```<code>$str = "Updated status to Masters - Software Engineering (Enrolled-
           Documents to Send) on 03/06/2014 14:10 by Rabih Haddad  .";

if(preg_match_all('/.*([A-Za-z]{3,4}, [A-Za-z]{3,4} [\d]{1,2}, [\d]{4}).*/',$str,$matches))
{
    print_r($matches);
}
 else
  echo "not matched";
</code>```

How can I extract date(03/06/2014) value from the string.

答:
Just look for the specific format you are after, 2 numbers then a forward slash, 2 more numbers then another forward slash, then 4 numbers.

```<code>\d{2}\/\d{2}\/\d{4}
</code>```

PHP Usage:

```<code>preg_match_all('/\d{2}\/\d{2}\/\d{4}/',$str,$matches)
</code>```

Demo: https://eval.in/811793

Your regex is looking for characters that aren't present. For example [A-Za-z]{3,4} [\d]{1,2}, [\d]
  {4}).* is looking for 3 or 4 alpha characters, a space 1-2 numbers, a comma, a space, a number, a new line, 4 spaces, and then anything after that.

Your {4} was correct you just needed to put it on the \d. The \d also doesn't need to be in a character class.

Body:
I need to extract the date from a string, below is my code and the string.

$str = "Updated status to Masters - Software Engineering (Enrolled-
           Documents to Send) on 03/06/2014 14:10 by Rabih Haddad  .";

if(preg_match_all('/.*([A-Za-z]{3,4}, [A-Za-z]{3,4} [\d]{1,2}, [\d]{4}).*/',$str,$matches))
{
    print_r($matches);
}
 else
  echo "not matched";

How can I extract date(03/06/2014) value from the string.

Body:
Just look for the specific format you are after, 2 numbers then a forward slash, 2 more numbers then another forward slash, then 4 numbers.

\d{2}\/\d{2}\/\d{4}

PHP Usage:

preg_match_all('/\d{2}\/\d{2}\/\d{4}/',$str,$matches)

Demo: https://eval.in/811793

Your regex is looking for characters that aren't present. For example [A-Za-z]{3,4} [\d]{1,2}, [\d]
  {4}).* is looking for 3 or 4 alpha characters, a space 1-2 numbers, a comma, a space, a number, a new line, 4 spaces, and then anything after that.

Your {4} was correct you just needed to put it on the \d. The \d also doesn't need to be in a character class.


问:
iOS Ad Hoc Distribution - starting 12 months testing period halfway through Apple Developer Program
Morning all,

We would like to release our app via Apples Ad Hoc distribution. We "can register up to 100 devices per product family per year that your team uses for development and testing." Our developer account is up for renewal on 20th January, but we want to release on 1st September. Does this mean that the app will stop working for testers on 20th January or will it run for 12 months from 1st September? We need it to run for 12 months from the initial release date, is there anything we need to be aware of to ensure this happens?

Huge thanks in anticipation of your help!

答: IOS certificate is only one year validity, after the need to re-apply for iOS authentication package IPA use</p>


问:
Scala: NoSuchMethodException when invoking mutable.ArrayBuffer（List，Int)
I want to invoke(List,Int) by reflecting, it's my code:

```<code>class TagCalculation {
  def test(arg1: scala.collection.immutable.$colon$colon[Any],arg2: java.lang.Integer) = "test mix2"
}
val getTest =  new TagCalculation

val arg1 : scala.collection.mutable.ArrayBuffer[Any] = scala.collection.mutable.ArrayBuffer()
arg1 += Array(1,2,3)

arg1 += 4

val argtypes4 = arg1.map(_.getClass)
val method4 = getTest.getClass.getMethod("test", argtypes4: _*)
method4.invoke(getTest,calcParamsArray.asInstanceOf[Seq[Object]]: _*)
</code>```

but method4 would some errors:

scala> val argtypes4 = arg1.map(.getClass) argtypes4:
  scala.collection.mutable.ArrayBuffer[Class[]] = ArrayBuffer(class [I,
  class java.lang.Integer)

scala> val method4 = getTest.getClass.getMethod("test", argtypes4: _*)
  java.lang.NoSuchMethodException: $iwC$$iwC$TagCalculation.test([I,
  java.lang.Integer)    at java.lang.Class.getMethod(Class.java:1678)   at
  $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:35)
    at
  $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:40)
    at
  $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:42)

Any idea to solve this issue?

答:
You are passing an Array[Int]

```<code>arg1 += Array(1,2,3)
</code>```

to the test method but the test method is expecting arg1: scala.collection.immutable.$colon$colon[Any]

So changing the test function to

```<code>def test(arg1: Array[Int],arg2: java.lang.Integer) = "test mix2"
</code>```

should work too

Body:
I want to invoke(List,Int) by reflecting, it's my code:

class TagCalculation {
  def test(arg1: scala.collection.immutable.$colon$colon[Any],arg2: java.lang.Integer) = "test mix2"
}
val getTest =  new TagCalculation

val arg1 : scala.collection.mutable.ArrayBuffer[Any] = scala.collection.mutable.ArrayBuffer()
arg1 += Array(1,2,3)

arg1 += 4

val argtypes4 = arg1.map(_.getClass)
val method4 = getTest.getClass.getMethod("test", argtypes4: _*)
method4.invoke(getTest,calcParamsArray.asInstanceOf[Seq[Object]]: _*)

but method4 would some errors:

scala> val argtypes4 = arg1.map(.getClass) argtypes4:
  scala.collection.mutable.ArrayBuffer[Class[]] = ArrayBuffer(class [I,
  class java.lang.Integer)

scala> val method4 = getTest.getClass.getMethod("test", argtypes4: _*)
  java.lang.NoSuchMethodException: $iwC$$iwC$TagCalculation.test([I,
  java.lang.Integer)    at java.lang.Class.getMethod(Class.java:1678)   at
  $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:35)
    at
  $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:40)
    at
  $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:42)

Any idea to solve this issue?

Body:
You are passing an Array[Int]

arg1 += Array(1,2,3)

to the test method but the test method is expecting arg1: scala.collection.immutable.$colon$colon[Any]

So changing the test function to

def test(arg1: Array[Int],arg2: java.lang.Integer) = "test mix2"

should work too


问:
Is possible to do this with a single query: get a fixed number of items of different types, ordered
Let's say i have a table with a "type" and a "date" column, and i want to fetch the latest 3 items of each type, ordered by date.(Can't trust the natural table order, or insertion order).
The query doesnt need to calculate all the different values for the "type" column, that can be specified in the query.

I'm trying with variables, like this:

```<code>set @c=0;
set @d=0;
select *, @c:=IF(type = 1, @c+1,@c), @d:=IF(type = 2, @d+1,@d) from testtable HAVING((type=1 AND @c < 3) OR (type=2 AND @d<3)) order by testdate;
</code>```

This is "almost" working, (it's returning one more entry for each type,which is fine), and i guess it's related to way mysql is resolving the HAVING clause (in fact, in some scenarios i'm finding i need to use WHERE instead of HAVING).Can someone shed some light in this? Am i safe using it like this?

答: Ok, looks that using HAVING is fine...I was having problems because, in my real code, i need to use a few order-by, and the last of those is RAND() (to resolve ties), and that RAND() ordering seems to mess up with the mysql variable assignment.</p>

Body:
Let's say i have a table with a "type" and a "date" column, and i want to fetch the latest 3 items of each type, ordered by date.(Can't trust the natural table order, or insertion order).
The query doesnt need to calculate all the different values for the "type" column, that can be specified in the query.

I'm trying with variables, like this:

set @c=0;
set @d=0;
select *, @c:=IF(type = 1, @c+1,@c), @d:=IF(type = 2, @d+1,@d) from testtable HAVING((type=1 AND @c < 3) OR (type=2 AND @d<3)) order by testdate;

This is "almost" working, (it's returning one more entry for each type,which is fine), and i guess it's related to way mysql is resolving the HAVING clause (in fact, in some scenarios i'm finding i need to use WHERE instead of HAVING).Can someone shed some light in this? Am i safe using it like this?


问:
mysql_result to mysqli issue
ive tried in vain for a good amount of time to convert this string from mysql to mysqli with no luck. here is what i had for mysql :

```<code>function user_exists($username) {
    $username = sanitize($username);
    $query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
    return (mysql_result($query, 0) == 1) ? true : false;
}
</code>```

ive tried:

```<code>function user_exists($username) {
    $link = mysqli_connect("localhost", "username", "password", "table");
    $username = sanitize($username);
    $usernamequery = "SELECT COUNT(`userid`) FROM `table` WHERE `username` = '$username' ";
    $query = mysqli_query($link, $usernamequery);
    $queryarray = mysqli_fetch_array($query, MYSQLI_BOTH);
    $queryarrayres = mysqli_num_rows($query)   ;
    if ($queryarrayres > 0) { true; } else { false;}
}
</code>```

numerous hits of this issue on here from previous users but none of them seem to work for me.this and this for example. it all seems fine until i get to converting the mysql_result query and it goes to pieces. i understand that mysql_result in the above situation is essentially checking to see if theres one row selected and thats it equal to one, ie present, but i just cant seem to get something equivalent in the mysqli.

```<code> function login($username, $password) {
    $link = mysqli_connect("localhost", "username", "pw", "db");
    $username = sanitize($username);
    $password = md5($password);
    $loginquery = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = $username AND `password` = $password";
    $query = mysqli_query($link, $loginquery);
    $queryarray = mysqli_fetch_array($query);
    $queryarrayres = $queryarray[0];
    return ($queryarrayres > 0)? $userid :false;
    }
</code>```

in this instance, $queryarrayres prints as 1 at the right occasion, and zero the rest. so that bit works. the function actually contains a password element too, which ive added.

unfortunately when i use the function is continually returns false. i have tested on a test page, and if i change $username and $password to absolute variable its seems to work. the code is identical between the old version (not shown), and this version, aside from the obvious mysqli updates. this narrows the issue down to three possibilities. 1) something to do with $username and $password population. 2) the $usernamequery string. 3) the return of the function. i reckon its three given that no other code has changed, but i cant put my finger on whats going on here.

答:
Use this function below, it works</p>

```<code>function user_id_from_username ($username){
     global $connect;
     $username = sanitize($username);
     $query = " SELECT  user_id FROM users WHERE username = '$username' ";
     $result = mysqli_query($connect, $query);
     $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
     echo $row["user_id"];
}
</code>```

Title: mysql_result to mysqli issue

Body:
ive tried in vain for a good amount of time to convert this string from mysql to mysqli with no luck. here is what i had for mysql :

function user_exists($username) {
    $username = sanitize($username);
    $query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
    return (mysql_result($query, 0) == 1) ? true : false;
}

ive tried:

function user_exists($username) {
    $link = mysqli_connect("localhost", "username", "password", "table");
    $username = sanitize($username);
    $usernamequery = "SELECT COUNT(`userid`) FROM `table` WHERE `username` = '$username' ";
    $query = mysqli_query($link, $usernamequery);
    $queryarray = mysqli_fetch_array($query, MYSQLI_BOTH);
    $queryarrayres = mysqli_num_rows($query)   ;
    if ($queryarrayres > 0) { true; } else { false;}
}

numerous hits of this issue on here from previous users but none of them seem to work for me.this and this for example. it all seems fine until i get to converting the mysql_result query and it goes to pieces. i understand that mysql_result in the above situation is essentially checking to see if theres one row selected and thats it equal to one, ie present, but i just cant seem to get something equivalent in the mysqli.

 function login($username, $password) {
    $link = mysqli_connect("localhost", "username", "pw", "db");
    $username = sanitize($username);
    $password = md5($password);
    $loginquery = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = $username AND `password` = $password";
    $query = mysqli_query($link, $loginquery);
    $queryarray = mysqli_fetch_array($query);
    $queryarrayres = $queryarray[0];
    return ($queryarrayres > 0)? $userid :false;
    }

in this instance, $queryarrayres prints as 1 at the right occasion, and zero the rest. so that bit works. the function actually contains a password element too, which ive added.

unfortunately when i use the function is continually returns false. i have tested on a test page, and if i change $username and $password to absolute variable its seems to work. the code is identical between the old version (not shown), and this version, aside from the obvious mysqli updates. this narrows the issue down to three possibilities. 1) something to do with $username and $password population. 2) the $usernamequery string. 3) the return of the function. i reckon its three given that no other code has changed, but i cant put my finger on whats going on here.

Body:
Use this function below, it works

function user_id_from_username ($username){
     global $connect;
     $username = sanitize($username);
     $query = " SELECT  user_id FROM users WHERE username = '$username' ";
     $result = mysqli_query($connect, $query);
     $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
     echo $row["user_id"];
}


问:
Apache spark dataframe
I have a column that has int values,

```<code> 2,43,1,25,3,13
</code>```

How do I create another column which has , multiply first two values and then next two and so on..

```<code>null,86,null,25,null,39
</code>```

Title: Apache spark dataframe

Body:
I have a column that has int values,

 2,43,1,25,3,13

How do I create another column which has , multiply first two values and then next two and so on..

null,86,null,25,null,39

Body:
spark = SparkSession.builder.appName('MyApp').getOrCreate()
rdd = spark.sparkContext.parallelize([2, 43, 1, 25, 3, 13]).zipWithIndex()
df = spark.createDataFrame(rdd, schema=['int_val', 'idx']).cache()
df_r = df.select(df['int_val'].alias('int_val_r'), (df['idx'] + 1).alias('idx_r'))
df = df.join(df_r, on=[df['idx'] == df_r['idx_r']], how='left_outer').orderBy(df['idx'])
df = df.withColumn('res', f.when(df['idx'] % 2 == 1, df['int_val'] * df['int_val_r']).otherwise(f.lit('null')))
df.show()

output:

+-------+---+---------+-----+----+
|int_val|idx|int_val_r|idx_r| res|
+-------+---+---------+-----+----+
|      2|  0|     null| null|null|
|     43|  1|        2|    1|  86|
|      1|  2|       43|    2|null|
|     25|  3|        1|    3|  25|
|      3|  4|       25|    4|null|
|     13|  5|        3|    5|  39|
+-------+---+---------+-----+----+


问:
Cannot set property 'fixed' of undefined webpack.js
Suddenly angular-cli "npm run build" is throwing error.

ERROR in main.fd5c1ee90c2680e9dd0f.bundle.js from UglifyJs
TypeError: Cannot set property 'fixed' of undefined

ERROR in main.6ff207bed7a4c7f21b38.bundle.js from UglifyJs
TypeError: Cannot set property 'fixed' of undefined
    at Object.eval [as visit] (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :5581:25)
    at Object._visit (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :1339:24)
    at AST_Node._walk (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :480:24)
    at AST_Node.eval (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :1061:29)
    at Object._visit (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :1343:21)
    at AST_Node._walk (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :1060:24)
    at AST_Node.walk (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :483:21)
    at Object.eval [as visit] (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :5719:31)
    at Object._visit (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :1339:24)
    at AST_Node._walk (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :653:24)
    at walk_body (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :530:17)
    at AST_Node.eval (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :541:13)
    at Object._visit (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :1343:21)
    at AST_Node._walk (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :540:24)
    at AST_Node.walk (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :483:21)
    at Object.eval [as visit] (eval at  (D:\project\Desktop\Hotfix\3\node_modules\webpack\node_modules\uglify-js\tools\node.js:1:0), :5698:42)

This is working with previous node_modules folder, now it is not working

答:
Refer to the comments in this question. Angular build failing due to Uglify.js

The way in which all the dependencies were arranged was an issue. There was a mismatch in the dependency flow and the sub dependencies were breaking the whole stuff. So I updated to the version of the angular that the project was using and then went around generating a new project. Compared the Package.json from the old and the new project. After that it required some adjustments and then the thing started working. There are other interesting points that you might find in the above link.


问:
Sending fax using Windows Fax Server Extentions - faxcomexlib
I'm trying to find faxcomexlib.dll.  After Googling around, I installed the Core SDK from the Platform SDK, but I still don't see this dll listed in the System32 folder. This is the code I'm trying to run:

```<code>FAXCOMEXLib.FaxServer faxServer = new FAXCOMEXLib.FaxServerClass();
                //faxServer.Connect(Environment.MachineName);
                faxServer.Connect("//My-Server");
                FAXCOMLib.FaxDoc faxDoc = (FAXCOMEXLib.FaxDoc)faxServer.CreateDocument(FileName);
                faxDoc.RecipientName = "Test";
                faxDoc.FaxNumber = "1234567890";
                faxDoc.DisplayName = "Test";
                int Response = faxDoc.Send();
                faxServer.Disconnect();
</code>```

I'm using VS 2010/.NET 4.0, and I'm on Windows XP.

答: You have to install Windows Fax Service and physical fax device on your computer to get that dll in the system 32</p>

Body:
I'm trying to find faxcomexlib.dll.  After Googling around, I installed the Core SDK from the Platform SDK, but I still don't see this dll listed in the System32 folder. This is the code I'm trying to run:

FAXCOMEXLib.FaxServer faxServer = new FAXCOMEXLib.FaxServerClass();
                //faxServer.Connect(Environment.MachineName);
                faxServer.Connect("//My-Server");
                FAXCOMLib.FaxDoc faxDoc = (FAXCOMEXLib.FaxDoc)faxServer.CreateDocument(FileName);
                faxDoc.RecipientName = "Test";
                faxDoc.FaxNumber = "1234567890";
                faxDoc.DisplayName = "Test";
                int Response = faxDoc.Send();
                faxServer.Disconnect();

I'm using VS 2010/.NET 4.0, and I'm on Windows XP.


问:
Python - Add tuple values to repeated keys in a dict
I've been trying to convert this test.csv file:

```<code>a,b,4
a,c,2
b,a,4
b,c,1
b,d,5
c,a,2
c,b,1
c,d,8
c,e,10
d,b,5
d,c,8
d,e,2
d,z,6
e,c,10
e,d,2
e,z,3
z,d,6
z,e,3
</code>```

Into this formatting. So far when I try to convert it, the repeated keys get override and not added as a second value. Could someone show me how to get this formatting?

```<code>G1 = {
    'a': [('b', 4), ('c', 2)],
    'b': [('a', 4), ('c', 1), ('d', 5)],
    'c': [('a', 2), ('b', 1), ('d', 8), ('e', 10)],
    'd': [('b', 5), ('c', 8), ('e', 2), ('z', 6)],
    'e': [('c', 10), ('d', 2), ('z', 3)],
    'z': [('d', 6), ('e', 3)],
}
</code>```

This is the code that converts the file into a dict, but replaces the new values for the repeated keys. I'd like to know how to add the values as tuples and for repeated keys, add the tuples as second values.

```<code>reader = csv.reader(open('test.csv'))
arcos = {}
for row in reader:
    key = row[0]
    arcos[key] = row[1:]
</code>```

And the result:

```<code>{
'a': ['c', 2.0],
 'b': ['d', 5.0],
 'c': ['e', 10.0],
 'd': ['z', 6.0],
 'e': ['z', 3.0],
 'z': ['e', 3.0]
}
</code>```

I hope what I've requested is possible.

答:
Use defaultdict with the list class, iterate the file and append the tuples:

```<code>from collections import defaultdict

G = defaultdict(list)

with open('test.csv') as file:
    for line in file:
        key, letter, digit = line.strip().split(',')
        digit = int(digit)
        G[key].append((letter, digit))
</code>```

Body:
I've been trying to convert this test.csv file:

a,b,4
a,c,2
b,a,4
b,c,1
b,d,5
c,a,2
c,b,1
c,d,8
c,e,10
d,b,5
d,c,8
d,e,2
d,z,6
e,c,10
e,d,2
e,z,3
z,d,6
z,e,3

Into this formatting. So far when I try to convert it, the repeated keys get override and not added as a second value. Could someone show me how to get this formatting?

G1 = {
    'a': [('b', 4), ('c', 2)],
    'b': [('a', 4), ('c', 1), ('d', 5)],
    'c': [('a', 2), ('b', 1), ('d', 8), ('e', 10)],
    'd': [('b', 5), ('c', 8), ('e', 2), ('z', 6)],
    'e': [('c', 10), ('d', 2), ('z', 3)],
    'z': [('d', 6), ('e', 3)],
}

This is the code that converts the file into a dict, but replaces the new values for the repeated keys. I'd like to know how to add the values as tuples and for repeated keys, add the tuples as second values.

reader = csv.reader(open('test.csv'))
arcos = {}
for row in reader:
    key = row[0]
    arcos[key] = row[1:]

And the result:

{
'a': ['c', 2.0],
 'b': ['d', 5.0],
 'c': ['e', 10.0],
 'd': ['z', 6.0],
 'e': ['z', 3.0],
 'z': ['e', 3.0]
}

I hope what I've requested is possible.

Body:
Use defaultdict with the list class, iterate the file and append the tuples:

from collections import defaultdict

G = defaultdict(list)

with open('test.csv') as file:
    for line in file:
        key, letter, digit = line.strip().split(',')
        digit = int(digit)
        G[key].append((letter, digit))


问:
How Can I Pull The Contacts Records from Salesforce in .NET Web API Connected Application
I have a connected Salesforce .NET Web Api Application and I'm trying to display all the contacts from that App.

```<code>public class ContactsController : ApiController
{
    public async Task<Models.Contact> Get()
    {
        var client = await SalesforceService.GetUserNamePasswordForceClientAsync();
        var contacts = await client.QueryAsync<Models.Contact>("SELECT id, FirstName, LastName, Email FROM Contact");
        var sfContact = contacts.Records;

        return sfContacts;
    }
}
</code>```

How do I return sfContacts?

答:
Update the controller action to return what ever type sfContacts is.

For example

```<code>public class ContactsController : ApiController {
    public async Task<List<Models.Contact>> Get() {
        var client = await SalesforceService.GetUserNamePasswordForceClientAsync();
        var contacts = await client.QueryAsync<Models.Contact>("SELECT id, FirstName, LastName, Email FROM Contact");
        var sfContact = contacts.Records;

        return sfContacts;
    }
}
</code>```

with the assumption being that contacts.Records returns a List<Models.Contact>

Or better yet use the IHttpActionResult abstraction methods of the ApiController

```<code>public class ContactsController : ApiController {
    public async Task<IHttpActionResult> Get() {
        var client = await SalesforceService.GetUserNamePasswordForceClientAsync();
        var contacts = await client.QueryAsync<Models.Contact>("SELECT id, FirstName, LastName, Email FROM Contact");
        var sfContact = contacts.Records
                                .Select(c => new {
                                    c.id,
                                    c.FirstName,
                                    c.LastName,
                                    c.Email
                                });

        return Ok(sfContacts);
    }
}
</code>```

The framework will take the sfContacts, whatever it is and serialize it in the response.

Body:
I have a connected Salesforce .NET Web Api Application and I'm trying to display all the contacts from that App.

public class ContactsController : ApiController
{
    public async Task<Models.Contact> Get()
    {
        var client = await SalesforceService.GetUserNamePasswordForceClientAsync();
        var contacts = await client.QueryAsync<Models.Contact>("SELECT id, FirstName, LastName, Email FROM Contact");
        var sfContact = contacts.Records;

        return sfContacts;
    }
}

How do I return sfContacts?

Body:
Update the controller action to return what ever type sfContacts is.

For example

public class ContactsController : ApiController {
    public async Task<List<Models.Contact>> Get() {
        var client = await SalesforceService.GetUserNamePasswordForceClientAsync();
        var contacts = await client.QueryAsync<Models.Contact>("SELECT id, FirstName, LastName, Email FROM Contact");
        var sfContact = contacts.Records;

        return sfContacts;
    }
}

with the assumption being that contacts.Records returns a List<Models.Contact>

Or better yet use the IHttpActionResult abstraction methods of the ApiController

public class ContactsController : ApiController {
    public async Task<IHttpActionResult> Get() {
        var client = await SalesforceService.GetUserNamePasswordForceClientAsync();
        var contacts = await client.QueryAsync<Models.Contact>("SELECT id, FirstName, LastName, Email FROM Contact");
        var sfContact = contacts.Records
                                .Select(c => new {
                                    c.id,
                                    c.FirstName,
                                    c.LastName,
                                    c.Email
                                });

        return Ok(sfContacts);
    }
}

The framework will take the sfContacts, whatever it is and serialize it in the response.


问:
Animating/transitioning text/textViews - android studio
Basically I have implemented a fade out function from one textView to another, and I'm wanting to know how I could fade out after delay or transition to other text after delay.

Java code:

```<code> if (event.getAction() == MotionEvent.ACTION_DOWN) {

            pView.setText("Nice");
            pView.startAnimation(AnimationUtils.loadAnimation(PlayScreen.this, android.R.anim.slide_in_left));
</code>```

The code works fine in my app and
I've found other questions that use other ways for animations but nothing useful to this method, or would it be better to use the valueAnimator?

答:
https://github.com/daimajia/AndroidViewAnimations
You can use this library it's very simple</p>

Body:
Basically I have implemented a fade out function from one textView to another, and I'm wanting to know how I could fade out after delay or transition to other text after delay.

Java code:

 if (event.getAction() == MotionEvent.ACTION_DOWN) {

            pView.setText("Nice");
            pView.startAnimation(AnimationUtils.loadAnimation(PlayScreen.this, android.R.anim.slide_in_left));

The code works fine in my app and
I've found other questions that use other ways for animations but nothing useful to this method, or would it be better to use the valueAnimator?


问:
Distribute ipa for Q&A (ad-hoc vs development-export)
Apple has this document which describes how to export your app for ad-hoc installation via iTunes.

One thing I am struggeling with is the differentiation between exporting for Ad-Hoc Deployment and exporting for Development Deployment.

I have the following circumstances:

The ipa should be installed via iTunes

All target-devices UUIDs are registred in the devcenter

The apple-id's installing those ipa's are NOT registred

Which option do I have to use and does that also always require me to generate an Ad Hoc-Profile as new iOS certificate?

答: Added udid's iOS certificate to install to the test device, IPA can not be sent directly to the phone installation.</p>