问:
Web API: different way of attribute routing
I am learning web api. just gone through few articles and found attribute routing can be done different way.

https://www.codeproject.com/Articles/774807/Attribute-Routing-in-ASP-NET-MVC-WebAPI

http://www.c-sharpcorner.com/UploadFile/b1df45/web-api-route-and-route-prefix-part-2/

https://www.codeproject.com/Articles/999691/RESTful-Day-sharp-Custom-URL-Re-Writing-Routing-us

See the code used:

```<code>[RoutePrefix("Movie")]
public class HomeController : Controller
{
      //Route: Movie/Index
      [Route]
      public ActionResult Index()
      {
           ViewBag.Message = "You are in Home Index";
           return View();
      }

      //Route: NewRoute/About
       [Route("~/NewRoute/About")]
       public ActionResult About()
       {
           ViewBag.Message = "You successfully reached NEWRoute/About route";
           return View();
       }
}
</code>```

in above example the author use Route attribute to define route for action.

see this one again

```<code>[GET("productid/{id?}")]
public HttpResponseMessage Get(int id)
{
    var product = _productServices.GetProductById(id);
    if (product != null)
        return Request.CreateResponse(HttpStatusCode.OK, product);
    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
}
</code>```

Here the author do not use route attribute rather use http verbs to define route.

So tell me which approach is right?

Another question that by attribute routine we can give different name to action then when one should use action name attribute to give different name to action?

When we can change action name by attribute routing then why should one use action name attribute to give different name to action?

答:
I believe [Route], RoutePrefix are those attributes which help us define the URL which we expose to the client browser.

Answer from

Patrick Hofman
  is well explanatory.

To indicate clearly how any written method works, there are HTTP verbs provided. Recently, I developed small Web API solution where I tried and tested Routing scenario with multiple attributes. Here they are:

```<code>[ActionName("GetIndex")]
[HttpGet]
public HttpResponseMessage IndexIdById(string id)
{
... other relative code here ...
var response = new HttpResponseMessage(HttpStatusCode.OK);
return response;
}
</code>```

If the method name is written without any Get prefix (as per above example)
it would give precise indication to specify [HttpGet] verb to show what the method is doing. Here this method is a Get method.

Also with such method name like above, it would be nicer to provide an alias name. [ActionName("GetIndex")]

To support such method with route configuration, we can provide route which maps Action name with other portion of the URL in WebApiConfig.cs. Example like below :-

```<code>config.Routes.MapHttpRoute(
name: "GetIndex",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: null
);
</code>```

I appreciate others advise or improvements to this answer. As this strategy to configure my Web API worked for me.

Body:
I am learning web api. just gone through few articles and found attribute routing can be done different way.

https://www.codeproject.com/Articles/774807/Attribute-Routing-in-ASP-NET-MVC-WebAPI

http://www.c-sharpcorner.com/UploadFile/b1df45/web-api-route-and-route-prefix-part-2/

https://www.codeproject.com/Articles/999691/RESTful-Day-sharp-Custom-URL-Re-Writing-Routing-us

See the code used:

[RoutePrefix("Movie")]
public class HomeController : Controller
{
      //Route: Movie/Index
      [Route]
      public ActionResult Index()
      {
           ViewBag.Message = "You are in Home Index";
           return View();
      }

      //Route: NewRoute/About
       [Route("~/NewRoute/About")]
       public ActionResult About()
       {
           ViewBag.Message = "You successfully reached NEWRoute/About route";
           return View();
       }
}

in above example the author use Route attribute to define route for action.

see this one again

[GET("productid/{id?}")]
public HttpResponseMessage Get(int id)
{
    var product = _productServices.GetProductById(id);
    if (product != null)
        return Request.CreateResponse(HttpStatusCode.OK, product);
    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
}

Here the author do not use route attribute rather use http verbs to define route.

So tell me which approach is right?

Another question that by attribute routine we can give different name to action then when one should use action name attribute to give different name to action?

When we can change action name by attribute routing then why should one use action name attribute to give different name to action?

Body:
I believe [Route], RoutePrefix are those attributes which help us define the URL which we expose to the client browser.

Answer from

Patrick Hofman
  is well explanatory.

To indicate clearly how any written method works, there are HTTP verbs provided. Recently, I developed small Web API solution where I tried and tested Routing scenario with multiple attributes. Here they are:

[ActionName("GetIndex")]
[HttpGet]
public HttpResponseMessage IndexIdById(string id)
{
... other relative code here ...
var response = new HttpResponseMessage(HttpStatusCode.OK);
return response;
}

If the method name is written without any Get prefix (as per above example)
it would give precise indication to specify [HttpGet] verb to show what the method is doing. Here this method is a Get method.

Also with such method name like above, it would be nicer to provide an alias name. [ActionName("GetIndex")]

To support such method with route configuration, we can provide route which maps Action name with other portion of the URL in WebApiConfig.cs. Example like below :-

config.Routes.MapHttpRoute(
name: "GetIndex",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: null
);

I appreciate others advise or improvements to this answer. As this strategy to configure my Web API worked for me.


来源: stackexchange

问:
JavaFx Include custom components in FXML
i try to find a solution on how to include custom javafx objects to a fxml file.

For example

```<code>package myExtendedObjects;

import javafx.scene.control.Label;

public class MyLabel extends Label interface connected{

    MyLabel(){
        super();
    }
  //Custom Code ...
}
</code>```

into fxml

```<code><?import myExtendedObjects.myLabel?>
<myLabel text="Name" />
</code>```

i alsways get error codes from the type javafx.fxml.LoadException:
Maybe there is a better solution then creating custom classes. But i need a Label with a custom Interface (connected). maybe a other solution would be to creata a fxml file wich includes only a label and set up a controller class for this with the interface.

EDIT:

```<code>try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/Viewer.fxml"));
        Parent root = fxmlLoader.load();
        Scene scene = new Scene(root);
        controller = fxmlLoader.getController();
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }
</code>```

EDITS 2:
After changing Names, i was able to import the custom object without error
but when i try to insert

```<code><MyLabel fx:id="myLabel"/>
</code>```

in my xml date i get this error

```<code>javafx.fxml.LoadException:
/C:/Users/TheOLGPC/Desktop/java/SolarimpactTelemety2/bin/fxml/Viewer.fxml:48

at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.constructValue(FXMLLoader.java:1013)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:746)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at application.Main.start(Main.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalAccessException: Class sun.reflect.misc.ReflectUtil can not access a member of class myExtendedObjects.MyLabel with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.constructValue(FXMLLoader.java:1009)
... 15 more
</code>```

Exception in Application start method

答:
Java has various naming conventions, including that class names should be capitalized, package names should be all lower case, and field and method names should begin lower case.

While the Java compiler and runtime regards these only as conventions, and will determine whether any entity is a class or property from the context, essentially regardless of name, the same is not true in FXML and for the FXMLLoader.

The FXML documentation states:

an element's tag is considered an instance declaration if the tag begins with uppercase letter

and later

Elements whose tag names begin with a lowercase letter represent object properties.

So if your classes fail to follow the usual naming conventions, they may fail to work correctly in FXML. Make sure the class and interface names are capitalized, property names are not capitalized, and package names are all lower case, and make sure they are used consistently in the Java code and in the FXML.

Additionally, the FXMLLoader will create an instance of your class by invoking (usually) the no-argument constructor. In order for that to work, the constructor must be public:

```<code>package myExtendedObjects;

import javafx.scene.control.Label;

public class MyLabel extends Label interface connected{

    public MyLabel(){
        super();
    }
  //Custom Code ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i try to find a solution on how to include custom javafx objects to a fxml file.

For example

package myExtendedObjects;

import javafx.scene.control.Label;

public class MyLabel extends Label interface connected{

    MyLabel(){
        super();
    }
  //Custom Code ...
}

into fxml

<?import myExtendedObjects.myLabel?>
<myLabel text="Name" />

i alsways get error codes from the type javafx.fxml.LoadException:
Maybe there is a better solution then creating custom classes. But i need a Label with a custom Interface (connected). maybe a other solution would be to creata a fxml file wich includes only a label and set up a controller class for this with the interface.

EDIT:

try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/Viewer.fxml"));
        Parent root = fxmlLoader.load();
        Scene scene = new Scene(root);
        controller = fxmlLoader.getController();
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }

EDITS 2:
After changing Names, i was able to import the custom object without error
but when i try to insert

<MyLabel fx:id="myLabel"/>

in my xml date i get this error

javafx.fxml.LoadException:
/C:/Users/TheOLGPC/Desktop/java/SolarimpactTelemety2/bin/fxml/Viewer.fxml:48

at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.constructValue(FXMLLoader.java:1013)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:746)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at application.Main.start(Main.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalAccessException: Class sun.reflect.misc.ReflectUtil can not access a member of class myExtendedObjects.MyLabel with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.constructValue(FXMLLoader.java:1009)
... 15 more

Exception in Application start method

Body:
Java has various naming conventions, including that class names should be capitalized, package names should be all lower case, and field and method names should begin lower case.

While the Java compiler and runtime regards these only as conventions, and will determine whether any entity is a class or property from the context, essentially regardless of name, the same is not true in FXML and for the FXMLLoader.

The FXML documentation states:

an element's tag is considered an instance declaration if the tag begins with uppercase letter

and later

Elements whose tag names begin with a lowercase letter represent object properties.

So if your classes fail to follow the usual naming conventions, they may fail to work correctly in FXML. Make sure the class and interface names are capitalized, property names are not capitalized, and package names are all lower case, and make sure they are used consistently in the Java code and in the FXML.

Additionally, the FXMLLoader will create an instance of your class by invoking (usually) the no-argument constructor. In order for that to work, the constructor must be public:

package myExtendedObjects;

import javafx.scene.control.Label;

public class MyLabel extends Label interface connected{

    public MyLabel(){
        super();
    }
  //Custom Code ...
}


问:
mysql select on two different tables depending on field-value
I have the following problem and my brain burns out :)

I have two tables with personal data (one for customer 'table_a' and one for interesting peoples 'table_b').
In a third table 'table_inv' there are entries with invited_persons from both tables (a nd b).

The table_inv has a field 'invited_id' in which the id from table a or table b is stored. Another field 'type' has the value 'cust' or 'interest' to separate from which table (a or b) the entry comes.

Now i have to get the full data from table_a / table_b depending on the value from field 'type'...

I tried it whith case and if but with no result.

I'm searching for something like this:

```<code>SELECT a.id, a.created, a.userid, a.type, a.inviteid, b.name_first, b.name_last, b.zip, b.city
FROM ext_event_invites a
CASE a.type
    WHEN 'CUST' THEN
        LEFT JOIN accounts b ON a.inviteid = b.id;
    ELSE
        LEFT JOIN ext_contacts b ON a.inviteid = b.id;
END CASE
WHERE a.eventid = :eventid AND a.userid = '4711'
ORDER BY b.name_last ASC, b.name_first ASC
</code>```

Can somebody help me?

答:
Please try this. This should work.</p>

```<code>SELECT a.id, a.created, a.userid, a.type, a.inviteid, b.name_first, b.name_last, b.zip, b.city
FROM ext_event_invites a
IF a.type = 'CUST' THEN
    LEFT JOIN accounts b ON a.inviteid = b.id;
ELSE
    LEFT JOIN ext_contacts b ON a.inviteid = b.id;
WHERE a.eventid = :eventid AND a.userid = '4711'
ORDER BY b.name_last ASC, b.name_first ASC
</code>```

Body:
I have the following problem and my brain burns out :)

I have two tables with personal data (one for customer 'table_a' and one for interesting peoples 'table_b').
In a third table 'table_inv' there are entries with invited_persons from both tables (a nd b).

The table_inv has a field 'invited_id' in which the id from table a or table b is stored. Another field 'type' has the value 'cust' or 'interest' to separate from which table (a or b) the entry comes.

Now i have to get the full data from table_a / table_b depending on the value from field 'type'...

I tried it whith case and if but with no result.

I'm searching for something like this:

SELECT a.id, a.created, a.userid, a.type, a.inviteid, b.name_first, b.name_last, b.zip, b.city
FROM ext_event_invites a
CASE a.type
    WHEN 'CUST' THEN
        LEFT JOIN accounts b ON a.inviteid = b.id;
    ELSE
        LEFT JOIN ext_contacts b ON a.inviteid = b.id;
END CASE
WHERE a.eventid = :eventid AND a.userid = '4711'
ORDER BY b.name_last ASC, b.name_first ASC

Can somebody help me?

Body:
Please try this. This should work.

SELECT a.id, a.created, a.userid, a.type, a.inviteid, b.name_first, b.name_last, b.zip, b.city
FROM ext_event_invites a
IF a.type = 'CUST' THEN
    LEFT JOIN accounts b ON a.inviteid = b.id;
ELSE
    LEFT JOIN ext_contacts b ON a.inviteid = b.id;
WHERE a.eventid = :eventid AND a.userid = '4711'
ORDER BY b.name_last ASC, b.name_first ASC


问:
How to parse String date to date object in ios swift?
I am parsing date from server into a custom format :-
This is the date :- "8/9/2017 3:58:00 AM" but it is not parsing into Date object using this format "MM/dd/yyyy hh:mm:ss a" because obviously the month, day and hour is single digit

As per my knowledge it should parse automatically because Android's DateFormat parses the same date.
This is the code snippet i am using :-

```<code>func getDateString(_ dateString:String) -> String{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "M/dd/yyyy hh:mm:ss a"
    let date = dateFormatter.date(from: dateString)
    dateFormatter.dateFormat = "dd MMM yyyy"
    return dateFormatter.string(from: date!)
}
</code>```

This function is returning null

答:
Your code should work, although you should also add some error-checking.

Try this (it will run in a Playground):

```<code>// returns an empty string "" if the date format is invalid
func getDateString(_ dateString:String) -> String {

    var strResult = ""

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "M/dd/yyyy hh:mm:ss a"

    if let date = dateFormatter.date(from: dateString) {
        dateFormatter.dateFormat = "dd MMM yyyy"
        strResult = dateFormatter.string(from: date)
    }

    return strResult

}

let dateString = getDateString("8/9/2017 3:58:00 AM")

print(dateString)   // prints "09 Aug 2017"
</code>```

If you change your "source" string to an invalid date/time - such as changing the month from 8 to 18 or the hour from 3 to 13 - you will see the returned value is an empty string.

Body:
I am parsing date from server into a custom format :-
This is the date :- "8/9/2017 3:58:00 AM" but it is not parsing into Date object using this format "MM/dd/yyyy hh:mm:ss a" because obviously the month, day and hour is single digit

As per my knowledge it should parse automatically because Android's DateFormat parses the same date.
This is the code snippet i am using :-

func getDateString(_ dateString:String) -> String{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "M/dd/yyyy hh:mm:ss a"
    let date = dateFormatter.date(from: dateString)
    dateFormatter.dateFormat = "dd MMM yyyy"
    return dateFormatter.string(from: date!)
}

This function is returning null

Body:
Your code should work, although you should also add some error-checking.

Try this (it will run in a Playground):

// returns an empty string "" if the date format is invalid
func getDateString(_ dateString:String) -> String {

    var strResult = ""

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "M/dd/yyyy hh:mm:ss a"

    if let date = dateFormatter.date(from: dateString) {
        dateFormatter.dateFormat = "dd MMM yyyy"
        strResult = dateFormatter.string(from: date)
    }

    return strResult

}

let dateString = getDateString("8/9/2017 3:58:00 AM")

print(dateString)   // prints "09 Aug 2017"

If you change your "source" string to an invalid date/time - such as changing the month from 8 to 18 or the hour from 3 to 13 - you will see the returned value is an empty string.


问:
Python: How to pip install opencv2 with specific version 2.4.9?
I know that I could pip install opencv-python which installs opencv3, but is there a separate command or name for opencv specific version such as 2.4.9?

If not, how can I specify which version to install?

Thanks.

答:
You can also do it using Anaconda: </p>

```<code>conda install -c https://conda.binstar.org/menpo opencv=2.4.9
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can also do it using Anaconda:

conda install -c https://conda.binstar.org/menpo opencv=2.4.9


问:
UWP - Google Analytics - Set Custom dimensions
I use UWP.SDKforGoogleAnalytics.managed and i had wrote these rows

```<code>Dim _TrakerId As String = "UA-XXXX0-0"

Dim MyTraker As GoogleAnalytics.Tracker = GoogleAnalytics.AnalyticsManager.Current.CreateTracker(_TrakerId) MyTraker.ScreenName = "Images"

Dim Hit = GoogleAnalytics.HitBuilder.CreateScreenView.Build

MyTraker.Send(Hit)
</code>```

All work good... BUT... now i'd like to use Custom dimensions.
Can anyone help me ??
Where can i set the value ?
Thanks

答:
I have custum dimension.
Before i had used another SDK..but with the old sdk i can't change the tracking ID...  Custom dimension before works good.

GoogleAnalytics.EasyTracker.GetTracker().SetCustomDimension(1, 'Title')    'Title
        GoogleAnalytics.EasyTracker.GetTracker().SetCustomDimension(2, 1234)  'ID

```<code>    GoogleAnalytics.EasyTracker.GetTracker().SendView("Images")
</code>```

Now with new SDK

Dim MyTraker As GoogleAnalytics.Tracker = GoogleAnalytics.AnalyticsManager.Current.CreateTracker(_TrakerId)

```<code>    MyTraker.ScreenName = "Image"

    Dim Vista = GoogleAnalytics.HitBuilder.CreateScreenView
    Vista.SetCustomDimension(1, 'Title')
    Vista.SetCustomDimension(2, 1234)  'ID

    MyTraker.Send(Vista.Build)
</code>```

in my opinion is correct...but not work :-(

Body:
I use UWP.SDKforGoogleAnalytics.managed and i had wrote these rows

Dim _TrakerId As String = "UA-XXXX0-0"

Dim MyTraker As GoogleAnalytics.Tracker = GoogleAnalytics.AnalyticsManager.Current.CreateTracker(_TrakerId) MyTraker.ScreenName = "Images"

Dim Hit = GoogleAnalytics.HitBuilder.CreateScreenView.Build

MyTraker.Send(Hit)

All work good... BUT... now i'd like to use Custom dimensions.
Can anyone help me ??
Where can i set the value ?
Thanks

Body:
I have custum dimension.
Before i had used another SDK..but with the old sdk i can't change the tracking ID...  Custom dimension before works good.

GoogleAnalytics.EasyTracker.GetTracker().SetCustomDimension(1, 'Title')    'Title
        GoogleAnalytics.EasyTracker.GetTracker().SetCustomDimension(2, 1234)  'ID

    GoogleAnalytics.EasyTracker.GetTracker().SendView("Images")

Now with new SDK

Dim MyTraker As GoogleAnalytics.Tracker = GoogleAnalytics.AnalyticsManager.Current.CreateTracker(_TrakerId)

    MyTraker.ScreenName = "Image"

    Dim Vista = GoogleAnalytics.HitBuilder.CreateScreenView
    Vista.SetCustomDimension(1, 'Title')
    Vista.SetCustomDimension(2, 1234)  'ID

    MyTraker.Send(Vista.Build)

in my opinion is correct...but not work :-(


问:
Spring MVC @PathVariable treated as @RequestParam
I have a spring mvc API (config in XML) with multiple services inside. But when I try to add a service with a @RequestMapping containing a path variable /{theCurrencyCode}, the resource created is not what I expected.

What I expected :

http://localhost:8080/api/v3/parameters/currencies/EUR

What works :

http://localhost:8080/api/v3/parameters/currencies/{theCurrencyCode}?theCurrencyCode=EUR

This is my mapping :

```<code>import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

  @RequestMapping(
      value = "/parameters/currencies/{theCurrencyCode}",
      produces = { "application/json" },
      method = RequestMethod.GET)
  ResponseEntity<List<Currency>> GetCurrencies(@PathVariable("theCurrencyCode") String theCurrencyCode);

}
</code>```

Implementation :

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

  private final CurrenciesService service;

  @Autowired
  public ParametersApiController(CurrenciesService service) {
    this.service = service;
  }

  @Override
  public ResponseEntity<List<Currency>> GetCurrencies(String code) {

    final List<Currency> currencies = service.getCurrencies(code);

    return new ResponseEntity<>(currencies, HttpStatus.OK);
  }
}
</code>```

Swagger UI confirmed this, seeing theCurrencyCode as a "Parameter Type" query instead of path.

How do I get my @PathVariable to work ?

答: Annotated method parameters are not being passed to all implementations. So that is why you need to redeclare it.</p>

Body:
I have a spring mvc API (config in XML) with multiple services inside. But when I try to add a service with a @RequestMapping containing a path variable /{theCurrencyCode}, the resource created is not what I expected.

What I expected :

http://localhost:8080/api/v3/parameters/currencies/EUR

What works :

http://localhost:8080/api/v3/parameters/currencies/{theCurrencyCode}?theCurrencyCode=EUR

This is my mapping :

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

  @RequestMapping(
      value = "/parameters/currencies/{theCurrencyCode}",
      produces = { "application/json" },
      method = RequestMethod.GET)
  ResponseEntity<List<Currency>> GetCurrencies(@PathVariable("theCurrencyCode") String theCurrencyCode);

}

Implementation :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

  private final CurrenciesService service;

  @Autowired
  public ParametersApiController(CurrenciesService service) {
    this.service = service;
  }

  @Override
  public ResponseEntity<List<Currency>> GetCurrencies(String code) {

    final List<Currency> currencies = service.getCurrencies(code);

    return new ResponseEntity<>(currencies, HttpStatus.OK);
  }
}

Swagger UI confirmed this, seeing theCurrencyCode as a "Parameter Type" query instead of path.

How do I get my @PathVariable to work ?


问:
Convert a JSON String to a HashMap
I'm using Java, and I have a String which is JSON:

```<code>{
"name" : "abc" ,
"email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]
}
</code>```

Then my Map in Java:

```<code>Map<String, Object> retMap = new HashMap<String, Object>();
</code>```

I want to store all the data from the JSONObject in that HashMap.

Can anyone provide code for this?  I want to use the org.json library.

答:
Hope this will work, try this:

```<code>import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);
</code>```

str, your JSON String

As Simple as this, if you want emailid,

```<code>String emailIds = response.get("email id").toString();
</code>```

Title: Convert a JSON String to a HashMap

Body:
I'm using Java, and I have a String which is JSON:

{
"name" : "abc" ,
"email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]
}

Then my Map in Java:

Map<String, Object> retMap = new HashMap<String, Object>();

I want to store all the data from the JSONObject in that HashMap.

Can anyone provide code for this?  I want to use the org.json library.

Body:
Hope this will work, try this:

import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);

str, your JSON String

As Simple as this, if you want emailid,

String emailIds = response.get("email id").toString();


问:
Salesforce Navigation Menu - remove home

I am very new to saleforce and playing around to get to know how things work.
How do i remove that home button there and can i move that cases and products menu items to right side?

Can you please help check

答:
You can use a CSS hack to hide the Home icon and option

Click on the Pen icon in the builder and then the CSS button next to the word Branding at the top.

```<code>.navigationMenuNode:first-child {
  display: none;
  visibility: hidden;
}
</code>```

Body:
You can use a CSS hack to hide the Home icon and option

Click on the Pen icon in the builder and then the CSS button next to the word Branding at the top.

.navigationMenuNode:first-child {
  display: none;
  visibility: hidden;
}


问:
Build Ionic Application From Xcode Project
I'm building an iOS application using Xcode/Swift, and I have a few less-than-technical group members who don't really know how to build Xcode projects, but are interested in seeing/testing the progress of the application.  One group member pointed out that they could test the app using Ionic/Ionic View.  However, to my understanding, Ionic works by building an application in the specific Ionic framework, and then Ionic translates the project into an Xcode/Swift project (.xcodeproj) or an Android project.  Is there a way to do the reverse conversion––is there a way to convert my Xcode project so that it will work on Ionic, or specifically Ionic View?  </p>

答:
Ionic is tool like cordova created to develop hybrid apps (from HTML+JS+CSS --> to Native iOS/Android/WinPhone/BlackBerry). The UI is running in native webView, and using some native functionalities by plugins but it is not created to make Ionic/Cordova app from native.

If you want to share your app to tests, use Apple TestFlight


问:
Addition of extract value from the string
I extracted value from the title as you can see. But I have problem with the addition. Basically I dont know how to add every .work-day-graph element in .ct-chart. So it will be like 1,25+8,25+0,75+0,5 = XY and 2,25+7,25+2,75+0,5 =XY. Any ideas ? Thanks a lot

DEMO: https://jsfiddle.net/1xn1eLfs/6/

JS:

```<code>$('.ct-chart').each(function() {
 var graphTitle;

 $(this).find('.work-day-graph').each(function() {
    graphTitle = $(this).attr('title');
    var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
    //graphTimeVal = graphTime.parseInt();

    $('<span class=output-val>' + graphTime + '</br>' + '</span>').appendTo('.output');
 });
});
</code>```

答:
Here's a modified JsFiddle:
https://jsfiddle.net/3woe2cdq/4/

If you want to display the sum for both charts, you need a separate output inside both of them to make it work.

```<code>$('.ct-chart').each(function() {
  var graphTitle;

  // Save the sum of the hours
  var graphTimeSum = 0;

  $(this).find('.work-day-graph').each(function() {
    graphTitle = $(this).attr('title');

    var graphTime = graphTitle
      .substring(graphTitle
        .lastIndexOf('(') + 1, graphTitle
        .lastIndexOf('h')
      ).replace(',', '.');

    // Add the current hours to the sum
    graphTimeSum += parseFloat(graphTime);
  });

  // Here we select the output class inside the chart
  $('<span class=output-val>' + graphTimeSum + '</br>' + '</span>').appendTo($(this).find('.output'));

});
</code>```

Body:
I extracted value from the title as you can see. But I have problem with the addition. Basically I dont know how to add every .work-day-graph element in .ct-chart. So it will be like 1,25+8,25+0,75+0,5 = XY and 2,25+7,25+2,75+0,5 =XY. Any ideas ? Thanks a lot

DEMO: https://jsfiddle.net/1xn1eLfs/6/

JS:

$('.ct-chart').each(function() {
 var graphTitle;

 $(this).find('.work-day-graph').each(function() {
    graphTitle = $(this).attr('title');
    var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
    //graphTimeVal = graphTime.parseInt();

    $('' + graphTime + '
' + '').appendTo('.output');
 });
});

Body:
Here's a modified JsFiddle:
https://jsfiddle.net/3woe2cdq/4/

If you want to display the sum for both charts, you need a separate output inside both of them to make it work.

$('.ct-chart').each(function() {
  var graphTitle;

  // Save the sum of the hours
  var graphTimeSum = 0;

  $(this).find('.work-day-graph').each(function() {
    graphTitle = $(this).attr('title');

    var graphTime = graphTitle
      .substring(graphTitle
        .lastIndexOf('(') + 1, graphTitle
        .lastIndexOf('h')
      ).replace(',', '.');

    // Add the current hours to the sum
    graphTimeSum += parseFloat(graphTime);
  });

  // Here we select the output class inside the chart
  $('<span class=output-val>' + graphTimeSum + '</br>' + '</span>').appendTo($(this).find('.output'));

});


问:
create a table without hardcode in html
I want to create a ten row five column table which has only two rows filled in it and also first cell of every row has a checkbox. I want to write entire table code in script of jquery but not define it as hardcode  data  in html page. I want it as an array instead of individual variables for each row.

```<code>$(document).ready(function() {
var table = [

{
  check: '<label><input type="checkbox" class="case" /><span></span>
  </label>',
  name: 'XYZ',
  score: '<div class="score">34</div>',
},
{
  check: '<label><input type="checkbox" class="case" /><span></span>
  </label>',
  name: 'XYZ',
  score: '<div class="score">34</div>',
},
{
  check: '<label><input type="checkbox" class="case" /><span></span>
  </label>',
  name: 'XYZ',
  score: '<div class="score">34</div>',
},

 $.each(table, function(index, obj)
 {
var row = '<tr>';
row += '<td>' + obj.check + '</td>';
row += '<td>' + obj.name + '</td>';
row += '<td>' + obj.score + '</td>';
row += '<td>' + obj.mail + '</td>';
row += '<td>' + obj.other + '</td>';
$('tbody').append(row);
});
</code>```

I dont want to declare objects every time. I want to use an array for defining "name, score, mail, other" and then push related items into that array variables

答:
If I've understood you correctly, this should provide what you need. Everything, including the columns, headings and contents, number of rows to render, and data to display is configured via an array of elements. There's no hard-coded HTML as such, it can all be manipulated via JavaScript.

I hope this is useful.

$(document).ready(function() {
//pre-defined array of columns and their base content
var cols = {
  "Check": $("<input/>", { "type": "checkbox", "class": "case" }),
  "Name": $("", { html: " " }),
  "Score": $("
", { "class": "score" }),
  "Mail": $("", { html: " " }),
  "Other": $("", { html: " " })
};

var trows = 10; //total rows to render
var data =
[
 { "Name": "ABC", "Score": 34, "Mail": "xyz", "Other": "blah" },
 { "Name": "DEF", "Score": 43, "Mail": "iii", "Other": "fff"}
];

for (var i = 0; i < trows; i++)
{
  var tr = $("
");

  $.each(cols, function(prop, element)
  {
    //only create the header once
    if (i == 0)
    {
      var th = $("", { "text": prop });
      $("#table1 thead tr").append(th);
    }

    var td = $("");

    if (element)
    {
      var cellContent = element.clone();
      if (data[i] && data[i][prop])
      {
        cellContent.text(data[i][prop]);
      }
      td.append(cellContent);
    }
    tr.append(td);
  });

  $("#table1 tbody").append(tr);
}

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
    border-collapse: collapse;
}
table td, table th { border: solid 1px #cccccc; padding:10px;  }</code>```

```

Title: create a table without hardcode in html

Body:
I want to create a ten row five column table which has only two rows filled in it and also first cell of every row has a checkbox. I want to write entire table code in script of jquery but not define it as hardcode  data  in html page. I want it as an array instead of individual variables for each row.

$(document).ready(function() {
var table = [

{
  check: '<input type="checkbox" class="case" />
  ',
  name: 'XYZ',
  score: '
34
',
},
{
  check: '<input type="checkbox" class="case" />
  ',
  name: 'XYZ',
  score: '
34
',
},
{
  check: '<input type="checkbox" class="case" />
  ',
  name: 'XYZ',
  score: '
34
',
},

 $.each(table, function(index, obj)
 {
var row = '
';
row += '' + obj.check + '	';
row += '' + obj.name + '	';
row += '' + obj.score + '	';
row += '' + obj.mail + '	';
row += '' + obj.other + '	';
$('tbody').append(row);
});

I dont want to declare objects every time. I want to use an array for defining "name, score, mail, other" and then push related items into that array variables

Body:
If I've understood you correctly, this should provide what you need. Everything, including the columns, headings and contents, number of rows to render, and data to display is configured via an array of elements. There's no hard-coded HTML as such, it can all be manipulated via JavaScript.

I hope this is useful.

$(document).ready(function() {
//pre-defined array of columns and their base content
var cols = {
  "Check": $("<input/>", { "type": "checkbox", "class": "case" }),
  "Name": $("<span/>", { html: "&nbsp;" }),
  "Score": $("<div/>", { "class": "score" }),
  "Mail": $("<span/>", { html: "&nbsp;" }),
  "Other": $("<span/>", { html: "&nbsp;" })
};

var trows = 10; //total rows to render
var data =
[
 { "Name": "ABC", "Score": 34, "Mail": "xyz", "Other": "blah" },
 { "Name": "DEF", "Score": 43, "Mail": "iii", "Other": "fff"}
];

for (var i = 0; i < trows; i++)
{
  var tr = $("<tr/>");

  $.each(cols, function(prop, element)
  {
    //only create the header once
    if (i == 0)
    {
      var th = $("<th/>", { "text": prop });
      $("#table1 thead tr").append(th);
    }

    var td = $("<td/>");

    if (element)
    {
      var cellContent = element.clone();
      if (data[i] && data[i][prop])
      {
        cellContent.text(data[i][prop]);
      }
      td.append(cellContent);
    }
    tr.append(td);
  });

  $("#table1 tbody").append(tr);
}

});

table {
    border-collapse: collapse;
}
table td, table th { border: solid 1px #cccccc; padding:10px;  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1">
  <thead>
    <tr>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>


问:
Cannot get divs to stack horizontally and be 100% of screen, in mobile view, while staying as 3 side-by-side in desktop
I have tried several solutions offered on this forum and none have worked.
Here is my code (I want 3 separate divs next to each other in desktop view, but to stack and fill 100% wide in mobile, on top each other)

Mobile Layout: 480px and below:

```<code>.gridContainer {
    width: 100%;
    overflow: hidden;
    background-color: #FFF;
        }
#bnr1 {
    float: left;
    display: block;
    color: #FFF;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 32px;
    text-align: left;
    padding-top: 5px;
    padding-right: 15px;
    padding-bottom: 15px;
    padding-left: 20px;
    margin-right: 5px;
    margin-bottom: 0px;
    margin-left: 0px;
    visibility: visible;
    overflow: visible;
    height: auto;
    background-color: #9C0;
    clear: right;
    width: 100%;
    margin-top: 0px;
}

#maincontent {
    width: auto;
    margin: 0px;
    padding: 0px;
}

#footer {
    clear: none;
    float: left;
    width: 100%;
    display: block;
    background-color: #000;
    font-family: Verdana, Geneva, sans-serif;
    font-size: 10px;
    color: #FFF;
    text-decoration: none;
    padding-left: 5px;
    text-align: center;
    margin-top: 10px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    padding-top: 5px;
    padding-right: 5px;
    padding-bottom: 5px;
}
#bnrpic {
    width: 70%;
    display: block;
    padding: 0px;
    overflow: visible;
    -webkit-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -moz-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -ms-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -o-transition: border-top-width, opacity 2000s ease-in-out 2s;
    margin-bottom: 5px;
    height: 400px;
    margin-top: 0px;
    margin-right: 0px;
    margin-left: 0px;
}
#LayoutDiv1 {
    text-align: left;
        }
#LayoutDiv2 {
    text-align: left;
    }
#LayoutDiv3 {
       text-align: left;
}
</code>```

答:
you may use "vh" unit for height property.
Basically it sets the size of your elements size via height of browser.
For details you can check.
https://web-design-weekly.com/2014/11/18/viewport-units-vw-vh-vmin-vmax/

Check this example code:

```<code><div class="main">1</div>
<div class="main">2</div>
<div class="main">3</div>
</code>```

and here is the css:

```<code>/*you have to reset browser to default to avoid problems*/
.main{
 width: 32%;
 height: 100px; /*any size you want*/
 background-color: black;
 float: left;

 /*Just for text and border*/
  border-right: 2px white solid;
  color: white;
  font-size: 600%;
  text-align: center;
  }

@media screen and (max-width: 480px) {
.main{
  width: 100%;
  height: 100vh;
  background-color: black;
  min-height: 200px;/*define your min-height
    because your content could mess*/

  /*Just for text and border*/
  border: none;
  border-bottom: 2px white solid;
 }
 }
</code>```

As you see, I define a new style for devices up to 400px (with vh unit).
The result should seem like that:
https://codepen.io/coderdisco/pen/VWvRdK

Body:
I have tried several solutions offered on this forum and none have worked.
Here is my code (I want 3 separate divs next to each other in desktop view, but to stack and fill 100% wide in mobile, on top each other)

Mobile Layout: 480px and below:

.gridContainer {
    width: 100%;
    overflow: hidden;
    background-color: #FFF;
        }
#bnr1 {
    float: left;
    display: block;
    color: #FFF;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 32px;
    text-align: left;
    padding-top: 5px;
    padding-right: 15px;
    padding-bottom: 15px;
    padding-left: 20px;
    margin-right: 5px;
    margin-bottom: 0px;
    margin-left: 0px;
    visibility: visible;
    overflow: visible;
    height: auto;
    background-color: #9C0;
    clear: right;
    width: 100%;
    margin-top: 0px;
}

#maincontent {
    width: auto;
    margin: 0px;
    padding: 0px;
}

#footer {
    clear: none;
    float: left;
    width: 100%;
    display: block;
    background-color: #000;
    font-family: Verdana, Geneva, sans-serif;
    font-size: 10px;
    color: #FFF;
    text-decoration: none;
    padding-left: 5px;
    text-align: center;
    margin-top: 10px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    padding-top: 5px;
    padding-right: 5px;
    padding-bottom: 5px;
}
#bnrpic {
    width: 70%;
    display: block;
    padding: 0px;
    overflow: visible;
    -webkit-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -moz-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -ms-transition: border-top-width, opacity 2000s ease-in-out 2s;
    -o-transition: border-top-width, opacity 2000s ease-in-out 2s;
    margin-bottom: 5px;
    height: 400px;
    margin-top: 0px;
    margin-right: 0px;
    margin-left: 0px;
}
#LayoutDiv1 {
    text-align: left;
        }
#LayoutDiv2 {
    text-align: left;
    }
#LayoutDiv3 {
       text-align: left;
}

Body:
you may use "vh" unit for height property.
Basically it sets the size of your elements size via height of browser.
For details you can check.
https://web-design-weekly.com/2014/11/18/viewport-units-vw-vh-vmin-vmax/

Check this example code:

<div class="main">1</div>
<div class="main">2</div>
<div class="main">3</div>

and here is the css:

/*you have to reset browser to default to avoid problems*/
.main{
 width: 32%;
 height: 100px; /*any size you want*/
 background-color: black;
 float: left;

 /*Just for text and border*/
  border-right: 2px white solid;
  color: white;
  font-size: 600%;
  text-align: center;
  }

@media screen and (max-width: 480px) {
.main{
  width: 100%;
  height: 100vh;
  background-color: black;
  min-height: 200px;/*define your min-height
    because your content could mess*/

  /*Just for text and border*/
  border: none;
  border-bottom: 2px white solid;
 }
 }

As you see, I define a new style for devices up to 400px (with vh unit).
The result should seem like that:
https://codepen.io/coderdisco/pen/VWvRdK


问:
Changing final structure of JSON file in a dataFrame using databricks?
I am using Databricks in python to change the final structure of a JSON file as a dataFrame.
To read it in Databricks one can use:

```<code>df = sqlContext.sql("SELECT * FROM people")
</code>```

While using Jupyter notebook you can do it easily with:

```<code>df = spark.read.json('people.json', schema = final_struc)
</code>```

But how does it work in databricks?

答:
Sometimes you should add the path name where your file is so it might work. Like

```<code>df = spark.read.json('FileStore/Something/people.json', schema = final_struc)
</code>```

Hope this works.

Body:
I am using Databricks in python to change the final structure of a JSON file as a dataFrame.
To read it in Databricks one can use:

df = sqlContext.sql("SELECT * FROM people")

While using Jupyter notebook you can do it easily with:

df = spark.read.json('people.json', schema = final_struc)

But how does it work in databricks?

Body:
Sometimes you should add the path name where your file is so it might work. Like

df = spark.read.json('FileStore/Something/people.json', schema = final_struc)

Hope this works.


问:
Including third-party libraries in C applications
I'm a bit naive when it comes to application development in C. I've been writing a lot of code for a programming language I'm working on and I want to include stuff from ICU (for internationalization and unicode support).

The problem is, I'm just not sure if there are any conventions for including a third party library. for something like readline where lots of systems are probably going to have it installed already, it's safe to just link to it (I think). But what about if I wanted to include a version of the library in my own code? Is this common or am I thinking about this all wrong?

答:
If your code requires 3rd party libraries, you need to check for them before you build. On Linux, at least with open-source, the canonical way to do this is to use Autotools to write a configure script that looks for both the presence of libraries and how to use them. Thankfully this is pretty automated and there are tons of examples. Basically you write a configure.ac (and/or a Makefile.am) which are the source files for autoconf and automake respectively. They're transformed into configure and Makefile.in, and ./configure conditionally builds the Makefile with any configure-time options you specify.

Note that this is really only for Linux. I guess the canonical way to do it on Windows is with a project file for an IDE...

ContentLicense: CC BY-SA 2.5


问:
JRE not found by eclipse
I am having issues starting up my java neon, and it keeps saying saying "A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run eclipse. no java virtual machine was found after searching the following locations C:/Program Files/Java/jre1.8.0_45/bin" but i installed the jre1.8.0_131, as i dont know how to either downgrade mine or update eclipse's. I feel so silly for not even knowing how to do this but thanks for any help you guys have!</p>

答:
Please edit the eclipse.ini which is located in the eclipse folder and specifiy the vm you want to use.

simply add two lines at the beginning of the file (set path to directory of your java installation)

```<code>-vm
C:/Program Files/Java/jdk1.8.0_121/bin/javaw.exe
</code>```

the other way is to check and update the environment variables JAVA_HOME and/or JRE_HOME.

Title: JRE not found by eclipse

Body:
Please edit the eclipse.ini which is located in the eclipse folder and specifiy the vm you want to use.

simply add two lines at the beginning of the file (set path to directory of your java installation)

-vm
C:/Program Files/Java/jdk1.8.0_121/bin/javaw.exe

the other way is to check and update the environment variables JAVA_HOME and/or JRE_HOME.


问:
Sagepay form Integration keeps giving error 5080 (Form transaction registration failed)
I have been trying to implement sage pay's form integration. Every time i submit a form i keep getting error code:5080 (Error description:  transaction registration failed). I tried searching for error code in sagepays website (https://www.sagepay.co.uk/support/error-codes) but apparently this error code doesn't exist.
If i type in the error description in sagepay's error code page, rather than the error code then i get the following result screenshot

However both my success url and failure url are present.

What is going on here?

Edit:

```<code> VendorTxCode=16-07-20-12-43-55-145161808&ReferrerID=&Amount=3,500.00&Currency=GBP&Description=Clarice Cliff SUNRAY LOTUS JUG C.1930&SuccessURL=http://test.co.uk/baskets/sagepay_success&FailureURL=http://test.co.uk/baskets/sagepay_failure&CustomerName=&CustomerEMail=&VendorEMail=&SendEMail=&eMailMessage=&BillingSurname=Tester&BillingFirstnames=Tester&BillingAddress1=Test Street&BillingAddress2=&BillingCity=London&BillingPostCode=TE14 1EE&BillingCountry=UNITED KINGDOM&BillingState=&BillingPhone=&DeliverySurname=Tester&DeliveryFirstnames=Tester&DeliveryAddress1=Test Street&DeliveryAddress2=&DeliveryCity=London&DeliveryPostCode=TE14 1EE&DeliveryCountry=UNITED KINGDOM&DeliveryState=&DeliveryPhone=&Basket=&AllowGiftAid=&ApplyAVSCV2=&Apply3DSecure=&BillingAgreement=&BasketXML=&CustomerXML=&SurchargeXML=&VendorData=&ReferrerID=&Language=&Website=
</code>```

答: On Woocomerce go to setting for Sagepay - make sure "select shipping address" is put to billing address instead of auto - simple fix. </p>

Body:
I have been trying to implement sage pay's form integration. Every time i submit a form i keep getting error code:5080 (Error description:  transaction registration failed). I tried searching for error code in sagepays website (https://www.sagepay.co.uk/support/error-codes) but apparently this error code doesn't exist.
If i type in the error description in sagepay's error code page, rather than the error code then i get the following result screenshot

However both my success url and failure url are present.

What is going on here?

Edit:

 VendorTxCode=16-07-20-12-43-55-145161808&ReferrerID=&Amount=3,500.00&Currency=GBP&Description=Clarice Cliff SUNRAY LOTUS JUG C.1930&SuccessURL=http://test.co.uk/baskets/sagepay_success&FailureURL=http://test.co.uk/baskets/sagepay_failure&CustomerName=&CustomerEMail=&VendorEMail=&SendEMail=&eMailMessage=&BillingSurname=Tester&BillingFirstnames=Tester&BillingAddress1=Test Street&BillingAddress2=&BillingCity=London&BillingPostCode=TE14 1EE&BillingCountry=UNITED KINGDOM&BillingState=&BillingPhone=&DeliverySurname=Tester&DeliveryFirstnames=Tester&DeliveryAddress1=Test Street&DeliveryAddress2=&DeliveryCity=London&DeliveryPostCode=TE14 1EE&DeliveryCountry=UNITED KINGDOM&DeliveryState=&DeliveryPhone=&Basket=&AllowGiftAid=&ApplyAVSCV2=&Apply3DSecure=&BillingAgreement=&BasketXML=&CustomerXML=&SurchargeXML=&VendorData=&ReferrerID=&Language=&Website=


问:
How to know when a UIViewController view is shown after being in the background?
In iOS4.2/iPhone4

Click icon to launch app (some view
controllers view is displayed)

Click iPhone Home button (return to
home screen)

double click Home button

Select previously launched app from
the selection

Now I can see that my app delegate gets a message "applicationDidBecomeActive" when its selected after the last step, but how does my viewController (the one who's view is currently displayed) know?

viewDidLoad was already called, so that isn't called again. viewWillLoad is not called again.

Can't seem to figure it out. Reason I'm asking is I want to check to see if any Settings changes were made, but would like to do that in the view controller cause that's the thing that cares.

答:
in you're appDelegate applicationDidBecomeActive put this :

```<code>- (void)applicationDidBecomeActive:(UIApplication *)application
{
    UINavigationController *navc = (UINavigationController *)[tabBarController selectedViewController];

    UIViewController *topvc = [navc topViewController];

    if ([topvc respondsToSelector:@selector(viewControllerDidBecomeActive)])
    {
        [topvc performSelector:@selector(viewControllerDidBecomeActive)];
    }
}
</code>```

This gets the viewController that is being seen on screen. You just have to implement viewControllerDidBecomeActive on every viewControllers ;)

Body:
in you're appDelegate applicationDidBecomeActive put this :

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    UINavigationController *navc = (UINavigationController *)[tabBarController selectedViewController];

    UIViewController *topvc = [navc topViewController];

    if ([topvc respondsToSelector:@selector(viewControllerDidBecomeActive)])
    {
        [topvc performSelector:@selector(viewControllerDidBecomeActive)];
    }
}

This gets the viewController that is being seen on screen. You just have to implement viewControllerDidBecomeActive on every viewControllers ;)


问:
Handling scala array group with ties
I have an array of names. I need to group by elements and select the name with highest count. If there are ties, then return the alphabetically last name. I have the below so far:

```<code>val names = Array("Adam", "Eve", "Adam", "Eve", "John", "Doe")
val countNames = names.map(x => (x, names.count(_ == x))).toSeq.sortBy(_._2)
</code>```

My result should be Eve. How can I get that?

答:
You can use the natural ordering of a (Int, String) tuple, and get the last element:

```<code>scala> names.map(x => (names.count(_ == x), x)).sorted.last._2
res0: String = Eve
</code>```

This would work as expected because this ordering would put the highest count last, and among tuples with same count would sort alphabetically, again placing "higher" alphabetical values last.

p.s. the grouping can also be done using groupBy:

```<code>names.groupBy(identity) // Map(Adam -> Array(Adam, Adam), Doe -> Array(Doe), Eve -> Array(Eve, Eve), John -> Array(John))
  .mapValues(_.length)  // Map(Adam -> 2, Doe -> 1, Eve -> 2, John -> 1)
  .toSeq.map(_.swap)    // ArrayBuffer((2,Adam), (1,Doe), (2,Eve), (1,John))
  .sorted               // ArrayBuffer((1,Doe), (1,John), (2,Adam), (2,Eve))
  .last._2              // Eve
</code>```

Title: Handling scala array group with ties

Body:
I have an array of names. I need to group by elements and select the name with highest count. If there are ties, then return the alphabetically last name. I have the below so far:

val names = Array("Adam", "Eve", "Adam", "Eve", "John", "Doe")
val countNames = names.map(x => (x, names.count(_ == x))).toSeq.sortBy(_._2)

My result should be Eve. How can I get that?

Body:
You can use the natural ordering of a (Int, String) tuple, and get the last element:

scala> names.map(x => (names.count(_ == x), x)).sorted.last._2
res0: String = Eve

This would work as expected because this ordering would put the highest count last, and among tuples with same count would sort alphabetically, again placing "higher" alphabetical values last.

p.s. the grouping can also be done using groupBy:

names.groupBy(identity) // Map(Adam -> Array(Adam, Adam), Doe -> Array(Doe), Eve -> Array(Eve, Eve), John -> Array(John))
  .mapValues(_.length)  // Map(Adam -> 2, Doe -> 1, Eve -> 2, John -> 1)
  .toSeq.map(_.swap)    // ArrayBuffer((2,Adam), (1,Doe), (2,Eve), (1,John))
  .sorted               // ArrayBuffer((1,Doe), (1,John), (2,Adam), (2,Eve))
  .last._2              // Eve


问:
JSP form action disabled: after adding Jquery Validation plugin. Need help on this
I created a form which will get input(like Student Name) , then submit button this name will pass to servlet as get method and works fine.

Post that I tried form validation using external jquery plugin, even that also worked fine. But the submit action got disabled.

##### Validation.js##
$(function(){
 jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
  });
 $("#myform").validate({
  rules:{

   StudentName:{
    required:true,
    minlength: 5,
       maxlength: 40

   }

  }

 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
  <script src="js/Validation.js"></script>
<form id="myform" action="addStudentContollerServlet" method="get">
   <input type="hidden" name="command" value="ADD"/>
   <table>
    <tbody>
      <tr>
       <td><label>StudentName :</label></td>
       <td><input type="text" name="StudentName" id="StudentName"/></td>
      </tr>
      <tr>
       <td><label></label></td>
       <td><input type="submit" value="Save"  class="save" /></td>
      </tr>

    </tbody>
   </table>
</form></code>```

答:
Found the answers:

```<code> by adding the below snippet it worked.
</code>```

$('#myform').submit(function (e) {
   e.preventDefault();
   if( $(this).valid() ) {
     $(this).unbind('submit');}

 });```

Body:
I created a form which will get input(like Student Name) , then submit button this name will pass to servlet as get method and works fine.

Post that I tried form validation using external jquery plugin, even that also worked fine. But the submit action got disabled.

##### Validation.js##
$(function(){
 jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
  });
 $("#myform").validate({
  rules:{

   StudentName:{
    required:true,
    minlength: 5,
       maxlength: 40

   }

  }

 });
});

<form id="myform" action="addStudentContollerServlet" method="get">
   <input type="hidden" name="command" value="ADD"/>

       StudentName :
       <input type="text" name="StudentName" id="StudentName"/>

       <input type="submit" value="Save"  class="save" />

</form>

Body:
Found the answers:

 by adding the below snippet it worked.

$('#myform').submit(function (e) {
   e.preventDefault();
   if( $(this).valid() ) {
     $(this).unbind('submit');}

 });


问:
psycopg2 - TypeError: 'int' object is not subscriptable
I'm performing the postgres query with psycopg2, stored in function columnsearch(). My aim is to be able to view the data in each field by using the column name in the return statement. I'm receiving the error:

```<code>TypeError: 'int' object is not subscriptable
</code>```

Does anyone know how I can rectify this?

```<code>def columnsearch():
     con = psycopg2.connect(connectstring)
     cur = con.cursor(cursor_factory=e.DictCursor)
     cur.execute("SELECT * FROM radio_archive_ind.radio_archive_ind WHERE tape_number = 'TP00001'")
     rows = cur.fetchone()
     for r in rows:
             return r["tape_number"]

print columnsearch()
</code>```

答:
Note that .fetchone() returns a single sequence so you can just do:

```<code>def columnsearch():
     con = psycopg2.connect(connectstring)
     cur = con.cursor(cursor_factory=e.DictCursor)
     cur.execute("""SELECT *
                      FROM radio_archive_ind.radio_archive_ind
                     WHERE tape_number = 'TP00001'""")
     row = cur.fetchone()
     return row["tape_number"]
</code>```

Body:
I'm performing the postgres query with psycopg2, stored in function columnsearch(). My aim is to be able to view the data in each field by using the column name in the return statement. I'm receiving the error:

TypeError: 'int' object is not subscriptable

Does anyone know how I can rectify this?

def columnsearch():
     con = psycopg2.connect(connectstring)
     cur = con.cursor(cursor_factory=e.DictCursor)
     cur.execute("SELECT * FROM radio_archive_ind.radio_archive_ind WHERE tape_number = 'TP00001'")
     rows = cur.fetchone()
     for r in rows:
             return r["tape_number"]

print columnsearch()

Body:
Note that .fetchone() returns a single sequence so you can just do:

def columnsearch():
     con = psycopg2.connect(connectstring)
     cur = con.cursor(cursor_factory=e.DictCursor)
     cur.execute("""SELECT *
                      FROM radio_archive_ind.radio_archive_ind
                     WHERE tape_number = 'TP00001'""")
     row = cur.fetchone()
     return row["tape_number"]


问:
Qlikview Moving Average
I have to create a stock turn report in Qlikview. For this report, I need to calculate the moving average of weekly stock based on last 13 weeks.

I can acheive this by the expression below:

```<code>RangeAvg(Above(sum(StockUnits),0,13))
</code>```

The problem is, the above expression will work only if I have all the weeks available in the report.If I filter this report by WK10 to WK30 then WK10 to WK23 will not have the average of last 13 weeks as weeks prior to WK10 is not displayed in the report.

Any help is very much appreciated.

Thanks.

答:
You can use set analysis within this expression to tell Qlik to ignore your selection of weeks.

Assuming your weeks field is called week, try:

```<code>RangeAvg(Above({$<week=>} sum(StockUnits),0,13))
</code>```

Title: Qlikview Moving Average

Body:
I have to create a stock turn report in Qlikview. For this report, I need to calculate the moving average of weekly stock based on last 13 weeks.

I can acheive this by the expression below:

RangeAvg(Above(sum(StockUnits),0,13))

The problem is, the above expression will work only if I have all the weeks available in the report.If I filter this report by WK10 to WK30 then WK10 to WK23 will not have the average of last 13 weeks as weeks prior to WK10 is not displayed in the report.

Any help is very much appreciated.

Thanks.

Body:
You can use set analysis within this expression to tell Qlik to ignore your selection of weeks.

Assuming your weeks field is called week, try:

RangeAvg(Above({$<week=>} sum(StockUnits),0,13))


问:
Select inner quotes that are between quotes
I wonder if you can help me with to figure out the regex to match inner quotes that are between quotes.

My problem is that I have an invalid JSON file that looks like

```<code>{
   "name" : "some "name" here",
   "lastName" : "some "lastname" here"
}
</code>```

As you may notice the inner double quotes are not escaped and I have an array with hundreds of records and some of them have that problem.
(I know that an invalid JSON cannot be read, so I am using fs from Node to get the string version of the JSON file)

```<code>fs.readFileSync('./bigJSON.json','utf8')
</code>```

I made this regex

```<code>/(?:\w\s)\".*\"(?:\s\w)/g
</code>```

that matches (e "name" h) and (e "lastname" h).
I wonder if there is a way to only target the nested quotes (").

I would appreciate some help.

答:
The problem is that regex is not good at finding unknown amounts of things.

This will find the first two unescaped quotes within a quoted string using negative lookbehinds

```<code>\"(?<!\\).*(\"(?<!\\)).*(\"(?<!\\)).*\"(?<!\\)
</code>```

where the two capture groups contain the offending unescaped quotes.  A slightly safer version would be

```<code>\"(?<!\\).*\"(?<!\\) : \"(?<!\\).*(\"(?<!\\)).*(\"(?<!\\)).*\"(?<!\\),?(?:\n|\r|\r\n)
</code>```

but requires your data to be fairly consistent.  This could be run multiple times, removing the found offending quotes until no more are found.

I would suggest that the best way to do this would be programmatically, as regex is no good at this, possibly as simply as reading the file character-by-character.

Update
Just noticed you are using Javascript.  According to http://regexr.com/, Javascript does not support positive or negative lookbehinds, although you should be correcting your file once before it is needed so could use any language.

Body:
I wonder if you can help me with to figure out the regex to match inner quotes that are between quotes.

My problem is that I have an invalid JSON file that looks like

{
   "name" : "some "name" here",
   "lastName" : "some "lastname" here"
}

As you may notice the inner double quotes are not escaped and I have an array with hundreds of records and some of them have that problem.
(I know that an invalid JSON cannot be read, so I am using fs from Node to get the string version of the JSON file)

fs.readFileSync('./bigJSON.json','utf8')

I made this regex

/(?:\w\s)\".*\"(?:\s\w)/g

that matches (e "name" h) and (e "lastname" h).
I wonder if there is a way to only target the nested quotes (").

I would appreciate some help.

Body:
The problem is that regex is not good at finding unknown amounts of things.

This will find the first two unescaped quotes within a quoted string using negative lookbehinds

\"(?<!\\).*(\"(?<!\\)).*(\"(?<!\\)).*\"(?<!\\)

where the two capture groups contain the offending unescaped quotes.  A slightly safer version would be

\"(?<!\\).*\"(?<!\\) : \"(?<!\\).*(\"(?<!\\)).*(\"(?<!\\)).*\"(?<!\\),?(?:\n|\r|\r\n)

but requires your data to be fairly consistent.  This could be run multiple times, removing the found offending quotes until no more are found.

I would suggest that the best way to do this would be programmatically, as regex is no good at this, possibly as simply as reading the file character-by-character.

Update
Just noticed you are using Javascript.  According to http://regexr.com/, Javascript does not support positive or negative lookbehinds, although you should be correcting your file once before it is needed so could use any language.


问:
angular 2 truncate length of the item
In my template I am display some values like

```<code><ion-card-content>
<chart *ngIf='item.isPublic' type="StockChart" [options]="options"></chart>
<ion-card-title>{{item.msg}}</ion-card-title>
<p class="card-text">{{item.time}}</p>
<p  class="card-text">{{item.agenda}}</p>
</ion-card-content>
</code>```

right now to control the length of values like item.agenda I have to do it in the component class.

Is there a way to display first say 20 char of item.agenda by applying some expression in the template itself?

答:
What you need is SlicePipe.

{{item.agenda | slice:0:20}}

Title: angular 2 truncate length of the item

Body:
In my template I am display some values like

<ion-card-content>
<chart *ngIf='item.isPublic' type="StockChart" [options]="options"></chart>
<ion-card-title>{{item.msg}}</ion-card-title>

{{item.time}}

{{item.agenda}}

</ion-card-content>

right now to control the length of values like item.agenda I have to do it in the component class.

Is there a way to display first say 20 char of item.agenda by applying some expression in the template itself?


问:
Redirect To Sub Folder By Country
I'm trying to separate the shop section of my website into US and UK sections as I offer different products to each country.

I'd like to use a sub folder ie. /us or /uk, but only when the customer goes into the shop section (clicks on shop, category or product).

I think the best way may be to create a shop. subdomain and activate an IP based redirect to the appropriate subfolder once they enter the shop. subdomain.

I'd could use a country selector pop-up (no need for redirect by IP) but I don't want two separate websites and I don't want my blog posts to be under the /us or /uk subfolders.

That's why I want to activate the redirect only when users click on the shop. section.

I'm using Worpress so if there are any plugins that would work I could use them.

If I had to use only subfolders (/shop/uk , /product/uk etc) then I could do that, but I can't find any advice that applies to my specific requirement.

答:
I would create a custom post type "shop" and then create a custom taxonomy.
Then add new custom taxonomy for each country and assign it to the custom post type "shop".

Register your custom post type in functions.php like so:

```<code>add_action( 'init', 'custom_post_types', 0 );
function custom_post_types() {

//shops
    register_post_type( 'shops',
        array(
            'labels' => array(
                'name' => __( 'Shops' ),
                'singular_name' => __( 'Shops' ),
                'all_items'  => __( 'All Shops'),
            ),
            'capabilities' => array(
                'edit_post'          => 'update_core',
                'read_post'          => 'update_core',
                'delete_post'        => 'update_core',
                'edit_posts'         => 'update_core',
                'edit_others_posts'  => 'update_core',
                'delete_posts'       => 'update_core',
                'publish_posts'      => 'update_core',
                'read_private_posts' => 'update_core'
            ),
            'taxonomies' => array('countries'),
            'menu_position' => 5,
            'public' => true,
            'has_archive' => false,
            'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt' ),
            "rewrite" => array(
                "slug"=>'news/%countries%',
                "with_front" => false
            ),
        )
    );
}
</code>```

Then register your custom taxonomy:

```<code>add_action( 'init', 'build_taxonomies', 0 );
function build_taxonomies() {
    register_taxonomy('countries', 'shops', array('hierarchical' => true, 'label' => 'Countries', 'query_var' => true, 'rewrite' => array( 'slug' => 'shops', 'with_front' => false)));
 }
</code>```

In order to use %countries%/ in the rewrite rule when registering your custom post type you need to tell WordPress what that means. You do it like so:

```<code>add_filter( 'post_type_link', 'wpa_shops_permalinks', 1, 2 );
function wpa_shops_permalinks( $post_link, $post ){
    if ( is_object( $post ) && $post->post_type == 'shops' ){
        $terms = wp_get_object_terms( $post->ID, 'countries' );
    if( $terms ){
        return str_replace( '%countries%' , $terms[0]->slug , $post_link );
    }
}
return $post_link;
}
</code>```

Title: Redirect To Sub Folder By Country

Body:
I would create a custom post type "shop" and then create a custom taxonomy.
Then add new custom taxonomy for each country and assign it to the custom post type "shop".

Register your custom post type in functions.php like so:

add_action( 'init', 'custom_post_types', 0 );
function custom_post_types() {

//shops
    register_post_type( 'shops',
        array(
            'labels' => array(
                'name' => __( 'Shops' ),
                'singular_name' => __( 'Shops' ),
                'all_items'  => __( 'All Shops'),
            ),
            'capabilities' => array(
                'edit_post'          => 'update_core',
                'read_post'          => 'update_core',
                'delete_post'        => 'update_core',
                'edit_posts'         => 'update_core',
                'edit_others_posts'  => 'update_core',
                'delete_posts'       => 'update_core',
                'publish_posts'      => 'update_core',
                'read_private_posts' => 'update_core'
            ),
            'taxonomies' => array('countries'),
            'menu_position' => 5,
            'public' => true,
            'has_archive' => false,
            'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt' ),
            "rewrite" => array(
                "slug"=>'news/%countries%',
                "with_front" => false
            ),
        )
    );
}

Then register your custom taxonomy:

add_action( 'init', 'build_taxonomies', 0 );
function build_taxonomies() {
    register_taxonomy('countries', 'shops', array('hierarchical' => true, 'label' => 'Countries', 'query_var' => true, 'rewrite' => array( 'slug' => 'shops', 'with_front' => false)));
 }

In order to use %countries%/ in the rewrite rule when registering your custom post type you need to tell WordPress what that means. You do it like so:

add_filter( 'post_type_link', 'wpa_shops_permalinks', 1, 2 );
function wpa_shops_permalinks( $post_link, $post ){
    if ( is_object( $post ) && $post->post_type == 'shops' ){
        $terms = wp_get_object_terms( $post->ID, 'countries' );
    if( $terms ){
        return str_replace( '%countries%' , $terms[0]->slug , $post_link );
    }
}
return $post_link;
}


问:
Show differences with another user in TFS
I have Eclipse Neon.

I want to show differences with my file and same file in another computer/user which I have permission to.

Can I do that? I know it's possible in Intellij.

答: Right-click on the source tree, and choose "View History." This will list all changesets that have been checked in to source control. You can right-click the changeset, and select "Compare." This will provide a dialog that lets you select the file to compare against.</p>


问:
How to read barcodes with the camera on Android?
I want my application to recognize barcodes taken by camera. Is it possible using Android SDK?

Something like this:
Barcode Scanner

答:
It's not built into the SDK, but you can use the Zxing library. It's free, open source, and Apache-licensed.

The 2016 recommendation is to use the Barcode API, which also works offline.


问:
Survey monkey c# console integration
Please anyone provide some examples on c# Survey monkey integration console application?</p>

答: Use SurveyMonkeyApi NuGet package.</p>

Title: Survey monkey c# console integration

Body: Use SurveyMonkeyApi NuGet package.


问:
How to represent a value from an object as boolean
The following object  is being returned from a SQL call:

```<code>#<Health:0x007fc8533f2de8 @type=:diabetic, @value="N", @data_source=nil, @measured_at=nil>
</code>```

The value could be 'Y' or 'N' and can be accessed as health.value.

How do I represent this value as a boolean?

答:
It's not clear from your question, but you seem to be using ActiveRecord.

If you are able to change the structure of the database, I would recommend doing so. Storing a boolean value as a string is not a good practice.

The boolean column type will store a native boolean value if the database supports it, and will translate if not. ActiveRecord automatically adds a predicate method to your model.

So if you have a boolean column named value, there will also be a method named value? that will return either true or false. "Automagical ?-methods for boolean attributes in ActiveRecord" is another example.

Body:
The following object  is being returned from a SQL call:

#<Health:0x007fc8533f2de8 @type=:diabetic, @value="N", @data_source=nil, @measured_at=nil>

The value could be 'Y' or 'N' and can be accessed as health.value.

How do I represent this value as a boolean?


问:
Release Branch and Continuous Delivery
Requirements

We have got 2 environments.
-- Test and Prod

We want to do Continuous Deployment.

We are using Git Flow.

With git-flow we are supposed to deploy the release (or master) branch in production. ( two different pipelines,one for continuous integration (branch develop) and one for continuous delivery (branch master).

How should I use my release branch ?

What I have in mind is if the tests pass in develop. I would make the CI server create a release branch commit. And deploy the updated release branch points to my productions staging slot. After business approval one of the release points would get deployed to production.

This means I am letting CI server automatically create a release-branch and re-run all the tests on staging slots of production environment. If it fails, it will report and delete the release branch, otherwise it will create the release point,trigger network swap and merge it to master.

What is the pros and cons to this approach ? What is the best practice ?

Do we really need the release branch especially where we are not using feature toggles to separate releases ? ( there are multiple people working on the same project )

][2

Reference

Feature Toggling, Youtube, https://www.youtube.com/watch?v=gxm1C92XhCQ

Successful Git Branching Model, http://nvie.com/posts/a-successful-git-branching-model/

答:
Typically I would create/cut a release branch when you think the code is close enough to stable. Then you need to refine that branch until it's release-ready. You would do extensive regression testing after this and then finally tag it and release it.

If you're doing true continuous releases then you might be skipping a lot of that testing so there isn't really a big point in even having a release branch. It's a lot riskier but you can do it if it fits your model.

Title: Release Branch and Continuous Delivery


问:
Firebase Synchronous XMLHttpRequest Deprecated
The ping service from Firebase is using Synchronous XMLHttpRequest which was reported by Google Chrome as follows:

Synchronous XMLHttpRequest on the main thread is deprecated because of
  its detrimental effects to the end user's experience. For more help,
  check http://xhr.spec.whatwg.org/.

The source of this issue is coming from:

```<code>.lp?dframe=t&id=612050&pw=gcdpSrzjvk&ns=myapp:5
</code>```

Is it a bug within Firebase? This isn't causing any issue for now. But in future, browsers may deprecate synchronous XHR.

答:
Yes, pretty sure this is a bug with Firebase. More specifically, I'm pretty sure this has to do with Firebase's service status. I consistently get this error any time there are intermittent service outages (which Firebase Support has subsequently acknowledged), then when the service is restored, the error no longer happens (presumably because WebSockets are working again, so the Firebase client is no longer falling back to XHR polling).

Also FWIW it seems to happen more frequently when developing locally than on live production servers, which hopefully means Firebase is prioritizing traffic properly.

Body:
The ping service from Firebase is using Synchronous XMLHttpRequest which was reported by Google Chrome as follows:

Synchronous XMLHttpRequest on the main thread is deprecated because of
  its detrimental effects to the end user's experience. For more help,
  check http://xhr.spec.whatwg.org/.

The source of this issue is coming from:

.lp?dframe=t&id=612050&pw=gcdpSrzjvk&ns=myapp:5

Is it a bug within Firebase? This isn't causing any issue for now. But in future, browsers may deprecate synchronous XHR.