问:
"Git bash here" and "Git GUI here" not working on Windows 10
I just installed Git for Window version 2.18.0 64-bit on a new Windows 10 machine (Win 10 Enterprise).

When I right-click in explorer and choose 'Git Bash Here' or 'Git Gui Here' I see an 'Application Not Found' error pop up.

Update

I found this answer which nearly helped me find the problem and the solution.

With regedit I was able to see that the HKEY_CURRENT_USER\Software\Classes\Directory\shell\git_shell\command was pointing to my user folder, instead of the actual location of git:

For "Git Bash Here", I changed the value to "C:\Program Files (x86)\Git\git-bash.exe" "--cd=%1"

Similarly for "Git GUI here", I changed the value for the HKEY_CURRENT_USER\Software\Classes\Directory\shell\git_gui\command to "C:\Program Files (x86)\Git\cmd\git-gui.exe" "--working-dir" "%1"

However, I still see the 'Application Not Found' error. Any ideas how to fix this?

答:
Delete following entries With regedit from Run Menu:

HKEY_CURRENT_USER\Software\Classes\Directory\shell\git_shell

HKEY_CURRENT_USER\Software\Classes\Directory\shell\git_gui

After this Reinstall application it will come .

It works for me.

Alternate option is also http://www.hoverdroids.com/errors/git/git-gui-here-and-git-bash-here-doesnt-work-resolved/


来源: stackexchange

问:
Unable to fetch all data from 2 tables using leftjoin
Iam unable to fetch all columns from the query, I got the result only 1 table, and Im expecting other table also, Here I have 2 tables a) registration_types and b)packages. I got the result of registration_types but I did not get the packages table

```<code>   return await createQueryBuilder("registration_types")
            .leftJoinAndSelect("packages", "pk", "pk.registration_type_id = registration_types.id")
            .getMany();
</code>```

I got the results, but not all the colums

答:
Hey you should try the following query:

```<code>return await createQueryBuilder("registration_types")
    .leftJoinAndSelect("registration_types.packages", Package, "pk", "pk.registration_type_id = registration_types.id")
    .getMany();
</code>```

OR

```<code>return await createQueryBuilder("registration_types")
    .leftJoinAndMapMany("registration_types.packages", Package, "pk", "pk.registration_type_id = registration_types.id")
    .getMany();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Iam unable to fetch all columns from the query, I got the result only 1 table, and Im expecting other table also, Here I have 2 tables a) registration_types and b)packages. I got the result of registration_types but I did not get the packages table

   return await createQueryBuilder("registration_types")
            .leftJoinAndSelect("packages", "pk", "pk.registration_type_id = registration_types.id")
            .getMany();

I got the results, but not all the colums

Body:
Hey you should try the following query:

return await createQueryBuilder("registration_types")
    .leftJoinAndSelect("registration_types.packages", Package, "pk", "pk.registration_type_id = registration_types.id")
    .getMany();

OR

return await createQueryBuilder("registration_types")
    .leftJoinAndMapMany("registration_types.packages", Package, "pk", "pk.registration_type_id = registration_types.id")
    .getMany();


问:
Concatenate string in typescript/javascript
EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.

I am trying to concatenate a string such that I get the following output:

```<code>"OR("1admin", "2admin")"
</code>```

But the output I keep on getting is

```<code>"OR(\"1admin\", \"2admin\")"
</code>```

Sample code

var str = "OR("
for (let i = 1; i < 3; i++) {
  str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)```
</div>
</div>
</p>

<p>I have tried using regex and string split.
eg.</p>

<p><code>.replace(/'/g, '"')</code> This when i tried something like this <code>"'" + i + "admin" + "', "</code> and tried to replace <code>'</code> with <code>"</code></p>

```.split('\\').join('').trim() This also didn' work.
```

What am I doing wrong?

答:
var str = '"OR("'
var adm = 'admin"'
var end = ')"'
for (let i = 1; i < 3; i++) {
  str += i + adm + ', '
}
str = str.trim().substring(0, str.length - 2)
str += end
console.log(str);```

try running this snippet. if the implementation is fyn for you. Result is what you expected.

Body:
EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.

I am trying to concatenate a string such that I get the following output:

"OR("1admin", "2admin")"

But the output I keep on getting is

"OR(\"1admin\", \"2admin\")"

Sample code

var str = "OR("
for (let i = 1; i < 3; i++) {
  str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)

I have tried using regex and string split.
eg.

.replace(/'/g, '"') This when i tried something like this "'" + i + "admin" + "', " and tried to replace ' with "

.split('\\').join('').trim() This also didn' work.

What am I doing wrong?

Body:
var str = '"OR("'
var adm = 'admin"'
var end = ')"'
for (let i = 1; i < 3; i++) {
  str += i + adm + ', '
}
str = str.trim().substring(0, str.length - 2)
str += end
console.log(str);

try running this snippet. if the implementation is fyn for you. Result is what you expected.


问:
Spring boot console app and user input not workking
I use spring boot 2
I try to create a console base application. When It start i would like to get some input of the user

```<code>@SpringBootApplication
public class ConsoleApplication implements CommandLineRunner {
    ...

    @Override
    public void run(String... args) throws Exception {

        Scanner reader = new Scanner(System.in);

        System.out.println("Enter file file path");
        this.filePath = reader.next();

        ...
    }

    public static void main(String[] args) {
        SpringApplication.run(ConsoleApplication.class, args);
    }

}
</code>```

When i try to run it

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at
  org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:776)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1242)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1230)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  com.sita.geodb.GeoDbApplication.main(GeoDbApplication.java:175)
  [main/:na] Caused by: java.util.NoSuchElementException: null  at
  java.util.Scanner.throwFor(Scanner.java:862) ~[na:1.8.0_131]  at
  java.util.Scanner.next(Scanner.java:1371) ~[na:1.8.0_131]     at
  com.sita.geodb.GeoDbApplication.run(GeoDbApplication.java:138)
  [main/:na]    at
  org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:792)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     ... 5 common frames
  omitted

答:
Please add the following line to your build.gradle file (assuming you use gradle as a build tool):

```<code>bootRun {
    standardInput = System.in
}
</code>```

This line wires the standard stdin to System.in

Body:
I use spring boot 2
I try to create a console base application. When It start i would like to get some input of the user

@SpringBootApplication
public class ConsoleApplication implements CommandLineRunner {
    ...

    @Override
    public void run(String... args) throws Exception {

        Scanner reader = new Scanner(System.in);

        System.out.println("Enter file file path");
        this.filePath = reader.next();

        ...
    }

    public static void main(String[] args) {
        SpringApplication.run(ConsoleApplication.class, args);
    }

}

When i try to run it

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at
  org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:776)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1242)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1230)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     at
  com.sita.geodb.GeoDbApplication.main(GeoDbApplication.java:175)
  [main/:na] Caused by: java.util.NoSuchElementException: null  at
  java.util.Scanner.throwFor(Scanner.java:862) ~[na:1.8.0_131]  at
  java.util.Scanner.next(Scanner.java:1371) ~[na:1.8.0_131]     at
  com.sita.geodb.GeoDbApplication.run(GeoDbApplication.java:138)
  [main/:na]    at
  org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:792)
  [spring-boot-2.0.8.RELEASE.jar:2.0.8.RELEASE]     ... 5 common frames
  omitted

Body:
Please add the following line to your build.gradle file (assuming you use gradle as a build tool):

bootRun {
    standardInput = System.in
}

This line wires the standard stdin to System.in


问:
How do I send data from Struts action to javascript?
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.

This is the list I'm trying to send/access:

```<code>List<MarkerClass> markers;
</code>```

MarkerClass is defined acoprding to belove:

```<code>final class MarkerClass
{
    public Integer objectId;
    public String street;
    public String streetNumber;
    public String zip;
    public String city;
    public Integer statusId;
    public Float lattitude;
    public Float longitude;
}
</code>```

The action also includes a getter for markers:

```<code>public List<MarkerClass> getMarkers()
{
    return markers;
}
</code>```

In my jsp-file I have tried doing this:

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function initialize()
{
    var titel = "";
    for(var i, "${markers}")
    {
        titel = titel+ "${markers[i].street}";
    }
}
</code>```

The browser substitutes "${markers}" with "[se.fubar.test.MarkerClass@37a4, se.fubar.test.MarkerClass@9ad97c]"

I'm guessing there is a better and smarter way to do this but since I'm a bit new to Struts and is trying to code while under the influence of a migrane the answer elludes me.

答:
you would have to set that variable in request or in session and then access it using a <c:out jsp tag like so

```<code>var myVar= '<c:out value="${requestScope.myVar}"/>';
</code>```

then use the var inside your js.

In case you set an object in request or session you have to use the get  method to access the value of an attribute then use it like so:

var myVar= '<c:out value="${requestScope.myObj.attribute}"/>';

(assuming you getter method is getAttribute)

it is not possible to access data in session or request directly from js
hope this helps

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.

This is the list I'm trying to send/access:

List<MarkerClass> markers;

MarkerClass is defined acoprding to belove:

final class MarkerClass
{
    public Integer objectId;
    public String street;
    public String streetNumber;
    public String zip;
    public String city;
    public Integer statusId;
    public Float lattitude;
    public Float longitude;
}

The action also includes a getter for markers:

public List<MarkerClass> getMarkers()
{
    return markers;
}

In my jsp-file I have tried doing this:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>

Body:
you would have to set that variable in request or in session and then access it using a <c:out jsp tag like so

var myVar= '<c:out value="${requestScope.myVar}"/>';

then use the var inside your js.

In case you set an object in request or session you have to use the get  method to access the value of an attribute then use it like so:

var myVar= '<c:out value="${requestScope.myObj.attribute}"/>';

(assuming you getter method is getAttribute)

it is not possible to access data in session or request directly from js
hope this helps


问:
istio allowing connection to HTTPS url without any service entry
I am using istio v1.0.6 and kubernetes 1.11. I was able to succesfully implement the ingress feature of istio.However, I am seeing that by default istio block the TCP connections from the mesh to applications outside cluster. But, it allows https connections to applications that are not even registered in the mesh.

Is there any default egress rules that I am missing ?

答:
Up until version 1.0, Istio’s default behavior was to block access to external endpoints . This created a connectivity issue and applications were breaking until the user could discover all the endpoints and configure them manually.

Istio 1.1 changed the default to allow access to all external endpoints.

See this for additional details and an automated way to generate serviceentries:
https://medium.com/@tufin/locking-down-istio-egress-with-automatic-traffic-discovery-51f0d49879a3


问:
Vuetify sparkline throws Error "Cannot read property 'getTotalLength' of undefined"
I want to have a simple sparkline in nuxt, but in the browser (chrome), in the console this error loged: [ERROR] [Vue warn]: Error in nextTick: "TypeError: Cannot read property 'getTotalLength' of undefined"

What I see in the browser is the chart draws once and then it disappears.

I almost sure that this error is due to auto-draw property. It is because, I changed other properties and nothing happened until I removed auto-draw and the error was gone.

```<code><v-sparkline
      auto-draw
      :value="value"
    ></v-sparkline>
</code>```

In the script section, here is the value:

```<code> data: () => ({
value: [100, 200, 300]
 })
</code>```

答:
I tried reproducing your error without success.
If you could provide some more context or try to reproduce your error in a codepen that would be helpful.

Here is a working codepen of your use case:
https://codepen.io/maxkoi/pen/Jqawjy

```<code><div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <v-sparkline
        :value="value"
        auto-draw
      ></v-sparkline>
    </v-container>
  </v-app>
</div>
</code>```

```<code>new Vue({
  el: '#app',
  data: () => ({
    value: [100, 200, 300]
  })
})
</code>```

Body:
I want to have a simple sparkline in nuxt, but in the browser (chrome), in the console this error loged: [ERROR] [Vue warn]: Error in nextTick: "TypeError: Cannot read property 'getTotalLength' of undefined"

What I see in the browser is the chart draws once and then it disappears.

I almost sure that this error is due to auto-draw property. It is because, I changed other properties and nothing happened until I removed auto-draw and the error was gone.

<v-sparkline
      auto-draw
      :value="value"
    ></v-sparkline>

In the script section, here is the value:

 data: () => ({
value: [100, 200, 300]
 })

Body:
I tried reproducing your error without success.
If you could provide some more context or try to reproduce your error in a codepen that would be helpful.

Here is a working codepen of your use case:
https://codepen.io/maxkoi/pen/Jqawjy

<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <v-sparkline
        :value="value"
        auto-draw
      ></v-sparkline>
    </v-container>
  </v-app>
</div>

new Vue({
  el: '#app',
  data: () => ({
    value: [100, 200, 300]
  })
})


问:
How to define accepting states in a finite automation?
I can build a finite automation from a dataset and would be glad to expand that to a deterministic finite automation (DFA). A DFA requires accepting states. How one can identify them, or how these can be defined?

Is there any proper definition for accepting states? What is the difference of accepting states from all other states?

答: After processing a string in your language as input, your deterministic finite automaton should end processing in an accepting state. On the other hand, after processing a string not in your language as input, your deterministic finite automaton should not end processing in an accepting state. You should choose your accepting states such that these two conditions hold for all the strings in your language.</p>


问:
SonarQube Proxy Configuration, Tricky
I cannot get the proxy configuration to work for SonarQube 4.0 so that I can install plugins.

When i open http://localhost:9000/updatecenter/available it displays the error: "Not connected to update center. Please check your internet connection and logs."

In sonar.log I read: "org.sonar.api.utils.HttpDownloader$HttpException: Fail to download [http://update.sonarsource.org/update-center.properties]. Response code: 403"

In sonar.properties I configured it with the same proxy which I use for other programs:

```<code>sonar.updatecenter.activate=true
http.proxyHost=<host>
http.proxyPort=<port>
http.proxyUser=<username>
http.proxyPassword=<password>
</code>```

I tried the same to configure in wrapper.properties, but it didn't work either by the way.

For the proxy host I tried the short and the full name. For the username I tried just the username and with <DOMAINNAME>\<username> and <DOMAINNAME>\\<username>.

Nothing of it worked. Any ideas?

答:
At sonar.properties set the proxy without "http://", only http.proxyHost=myproxy.domain.pt

Another suggestion is to also add this lines on wrapper.conf:

```<code>wrapper.java.additional.3=-Dhttp.proxySet=true
wrapper.java.additional.4=-Dhttp.proxyHost=myproxy.domain.pt
wrapper.java.additional.5=-Dhttp.proxyPort=myproxy.port
wrapper.java.additional.6=-Dhttps.proxyHost=myproxy.domain.pt
wrapper.java.additional.7=-Dhttps.proxyPort=myproxy.port
</code>```

Careful if you have a docker volume, remove it before deploy the new one with this configuration, or otherwise it will keep the original configuration

Title: SonarQube Proxy Configuration, Tricky

Body:
I cannot get the proxy configuration to work for SonarQube 4.0 so that I can install plugins.

When i open http://localhost:9000/updatecenter/available it displays the error: "Not connected to update center. Please check your internet connection and logs."

In sonar.log I read: "org.sonar.api.utils.HttpDownloader$HttpException: Fail to download [http://update.sonarsource.org/update-center.properties]. Response code: 403"

In sonar.properties I configured it with the same proxy which I use for other programs:

sonar.updatecenter.activate=true
http.proxyHost=<host>
http.proxyPort=<port>
http.proxyUser=<username>
http.proxyPassword=<password>

I tried the same to configure in wrapper.properties, but it didn't work either by the way.

For the proxy host I tried the short and the full name. For the username I tried just the username and with <DOMAINNAME>\<username> and <DOMAINNAME>\\<username>.

Nothing of it worked. Any ideas?

Body:
At sonar.properties set the proxy without "http://", only http.proxyHost=myproxy.domain.pt

Another suggestion is to also add this lines on wrapper.conf:

wrapper.java.additional.3=-Dhttp.proxySet=true
wrapper.java.additional.4=-Dhttp.proxyHost=myproxy.domain.pt
wrapper.java.additional.5=-Dhttp.proxyPort=myproxy.port
wrapper.java.additional.6=-Dhttps.proxyHost=myproxy.domain.pt
wrapper.java.additional.7=-Dhttps.proxyPort=myproxy.port

Careful if you have a docker volume, remove it before deploy the new one with this configuration, or otherwise it will keep the original configuration


问:
How to remove myself from a Firebase project
I decided to try Firebase. When I go to the console, I not only see my own project, but two projects that I never created or was supposed to have access to:

Those projects seem to be created by a "Rohit Travel & Tours". I can see some of the details:

When I go to Google Cloud's resource manager, sure enough, the project is also there, along with a few "My First Project" projects that seem to belong to the same people:

I'm not sure why I got access to this. It's either a dangerous bug, or a clueless admin that added one of my emails to the project.

I'd like to remove that project since it's just clutter. However, I can't find a way to remove myself from the project, and since I don't have any kind of admin access, there's nothing I can actually change there. In fact, I can't find my account listed on any of the role/member fields either, so I'm not sure what's the real story there.

So far the admin emails listed on the accounts have been unresponsive when I requested that my account be removed.

There's no way to contact Google Cloud to request that either. Apparently the only way to contact them is with a paid support account of some kind.

So my question is: is there a way for me to ever remove myself from these accounts, so I don't see them on my panels, especially the Firebase dashboard?

Or am I stuck with these app accounts forever?

答:
When such projects show up for me, it's usually because someone added a group that I'm a member of (like all@company.com) as a collaborator to that project. If that is the cause, there is no way to remove me/you as an individual user. One of the owners on the project will have to remove the overly broad group, and replace it by either a better targeted group or by the individual users.

Also see:

How do I remove myself from a project in the Google Developer Console?


问:
Expression not working against EF4.1
Is there someone who can please explain why the following  is not working??:
the model is defined like this (very simple version)

```<code> public class Monument
{
        [Key]
        public int? MonumentId { get; set; }
        public string Name { get; set; }
}
</code>```

The Find method in my repository implementation is defined like this:

```<code>public virtual IQueryable<T> Find(Expression<Func<T, bool>> where)
{
    return _dbset.Where(where);
}
</code>```

The where parameter gets a value this way:

```<code> whereClause = c => (   (FilteringRecord.MonumentId <= 0 ?
true : c.MonumentId == FilteringRecord.MonumentId)

&& (String.IsNullOrEmpty(FilteringRecord.Name) ?
true :c.Name.Contains(FilteringRecord.Name))        );
</code>```

So if the value of FilteringRecord.MonumentId is equal to a number i get the desired record, but if the FilteringRecord.Name has a value it's completely ignored!! Why???

The same works fine on the first version of Entity Framework or LINQ to SQL!!

Thanks in advance!!

答: Turns out that the expression is working as expected! The error was caused by a wrong binding in the UI (this is a WPF application), giving wrong values to FilteringRecord!</p>

Title: Expression not working against EF4.1

Body:
Is there someone who can please explain why the following  is not working??:
the model is defined like this (very simple version)

 public class Monument
{
        [Key]
        public int? MonumentId { get; set; }
        public string Name { get; set; }
}

The Find method in my repository implementation is defined like this:

public virtual IQueryable<T> Find(Expression<Func<T, bool>> where)
{
    return _dbset.Where(where);
}

The where parameter gets a value this way:

 whereClause = c => (   (FilteringRecord.MonumentId <= 0 ?
true : c.MonumentId == FilteringRecord.MonumentId)

&& (String.IsNullOrEmpty(FilteringRecord.Name) ?
true :c.Name.Contains(FilteringRecord.Name))        );

So if the value of FilteringRecord.MonumentId is equal to a number i get the desired record, but if the FilteringRecord.Name has a value it's completely ignored!! Why???

The same works fine on the first version of Entity Framework or LINQ to SQL!!

Thanks in advance!!


问:
How to response different data that was inserted by create method (ModelViewSet)
I'm implementing a stock shoes manager with REST architecture using Django + Django rest.

Im using a custom Router inherited from DefaultRouter to serve my endpoints.

In the /resources/id endpoint Ive added one more verb, POST that is called  by custom_create method.

Here you can see this custom_create method:

viewsets.py

```<code>
class ShoeViewSet(viewsets.ModelViewSet):

    queryset = Shoe.objects.all()
    filter_class = ShoeFilter

    def get_serializer_class(self):
        if self.action == 'custom_create':
            return StockPostSerializer
        else:
            return ShoeSerializer

    def custom_create(self, request, *args, **kwargs):
        data = {}

        data['shoe'] = kwargs['pk']
        data['size'] = request.data.get('size')
        data['amount'] = request.data.get('amount')

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

</code>```

I needed to do this because I have two models, below you can see my 3 Serializers:

serializers.py

```<code>class StockSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['size', 'amount']

class ShoeSerializer(serializers.ModelSerializer):
    stock = StockSerializer(many=True, read_only=True)

    class Meta:
        model = Shoe
        fields = ['description', 'provider', 'type', 'cost_price','sale_price','total_amount', 'stock']

class StockPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['shoe','size', 'amount']
</code>```

The retrieve (GET verb) method of this endpoint expects data serialized by ShoeSerializer, but the custom_create method insert data using the StockPostSerializer. How can I return a response with a different data that was inserted ?

When I try to insert with this endpoint I recieve this error message, but when I refresh the page I realize that the content was inserted (If i use postman instead of de DRF frontend I dont get any error message, works fine).

How can my custom_create method Responses correctly ?

You can check my github, the names will be a bit different because I translated it here so that it is easier for you to understand.

PS: As you may have noticed I am not a native speaker of the English language, so it is very difficult to express myself here but I am trying my best, and learning more and more. If my question contains grammar / concordance errors please correct them but you do not have to refuse me so I'm trying to learn!

答:
If I understood correctly by looking at your code, in this case specifically, you don't need the StockPostSerializer. You can acheive the result you want by changing StockSerializer as follows:

```<code>class StockSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['shoe', 'size', 'amount']
        extra_kwargs = {'shoe': {'write_only': True}}
</code>```

I greatly apologize if I misunderstood your question.

EDIT:

Forgot to say. Using this serializer you don't need any extra route on your ModelViewSet

Body:
I'm implementing a stock shoes manager with REST architecture using Django + Django rest.

Im using a custom Router inherited from DefaultRouter to serve my endpoints.

In the /resources/id endpoint Ive added one more verb, POST that is called  by custom_create method.

Here you can see this custom_create method:

viewsets.py

class ShoeViewSet(viewsets.ModelViewSet):

    queryset = Shoe.objects.all()
    filter_class = ShoeFilter

    def get_serializer_class(self):
        if self.action == 'custom_create':
            return StockPostSerializer
        else:
            return ShoeSerializer

    def custom_create(self, request, *args, **kwargs):
        data = {}

        data['shoe'] = kwargs['pk']
        data['size'] = request.data.get('size')
        data['amount'] = request.data.get('amount')

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

I needed to do this because I have two models, below you can see my 3 Serializers:

serializers.py

class StockSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['size', 'amount']

class ShoeSerializer(serializers.ModelSerializer):
    stock = StockSerializer(many=True, read_only=True)

    class Meta:
        model = Shoe
        fields = ['description', 'provider', 'type', 'cost_price','sale_price','total_amount', 'stock']

class StockPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['shoe','size', 'amount']

The retrieve (GET verb) method of this endpoint expects data serialized by ShoeSerializer, but the custom_create method insert data using the StockPostSerializer. How can I return a response with a different data that was inserted ?

When I try to insert with this endpoint I recieve this error message, but when I refresh the page I realize that the content was inserted (If i use postman instead of de DRF frontend I dont get any error message, works fine).

How can my custom_create method Responses correctly ?

You can check my github, the names will be a bit different because I translated it here so that it is easier for you to understand.

PS: As you may have noticed I am not a native speaker of the English language, so it is very difficult to express myself here but I am trying my best, and learning more and more. If my question contains grammar / concordance errors please correct them but you do not have to refuse me so I'm trying to learn!

Body:
If I understood correctly by looking at your code, in this case specifically, you don't need the StockPostSerializer. You can acheive the result you want by changing StockSerializer as follows:

class StockSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['shoe', 'size', 'amount']
        extra_kwargs = {'shoe': {'write_only': True}}

I greatly apologize if I misunderstood your question.

EDIT:

Forgot to say. Using this serializer you don't need any extra route on your ModelViewSet


问:
How to purchase more licences for a Microsoft Subscription via the API
I am attempting to automatically add a Power BI Pro Licence to Office account in the domain that i manage and i am getting stuck when i Don't have enough Licences to assign another

I can do the 'Assigning' part using https://graph.microsoft.com/v1.0/users/{id}/assignLicense which works until there aren't any spare licences, where it returns: "Subscription with SKU {id} does not have any available licenses."

To make this a fully automated process, i need to:

Automatically purchase a new Power BI Licence.

Assign that Licence to a user.

I cannot identity an API endpoint which allows me to do step 1.

答: Microsoft Graph, nor any other Microsoft API, supports purchasing O365 licenses. That is done through their Microsoft rep (if they have one) or through the Admin Portal directly.</p>


问:
Route53 hosted zone fails redirect to ELB
I have a ELB set and running smooth. It's exposed on internet using URL http://acdd3f11b813911e9b3bf1209a60fe34-1652245676.us-east-1.elb.amazonaws.com/.

If you try to open this link, you'll see a nginx page. I've created a record set inside my hosted zone to run a few tests (nginx.melic.com.br) but it's keep failing and when I try to traceroute I got an error traceroute: unknown host nginx.melic.com.br.

Anyone has an idea how to debug what's going on?

答: Most likely your DNS zone entries are not accurate. Check the DNS entry for your domain, and make sure you have aliased it with ELB resource host.</p>


问:
Rotate google map with vue2-google-maps
I want to turn the map 90 degrees. How can I do ? I use vue2-google-maps to create a map.</p>

```<code>        <GmapMap
          id="map"
          :center="{lat:latitude, lng:longitude}"
          map-type-id="satellite"
          style="width: 100vw; height: 100vh"
          :zoom= zoom
          :tilt="rotate" // 45
          :options="{
            rotateControl: true,
            minZoom:5,
            maxZoom:20,
          }"
      />
</code>```

答:
According to documentation :

Once your map is displaying 45° imagery, you can orient the imagery
  towards one of its cardinal directions by calling setHeading() on the
  Map object, passing a number value expressed as degrees from North.

So, orient the imagery ( heading property) could be specified once 45° imagery is set, here is an example for vue-google-maps

```<code><template>
  <div>
    <GmapMap
       :center="center"
      :zoom="zoom"
      :mapTypeId="'satellite'"
      :tilt="titl"
      :heading="heading"
       ref="map">

    </GmapMap>
  </div>
</template>

<script>
export default {
  data() {
    return {
      zoom: 18,
      center: { lat: 45.518, lng: -122.672 },
      titl: 45,
      heading: 90
    };
  },
  methods: {}
};
</script>
</code>```

Title: Rotate google map with vue2-google-maps

Body:
I want to turn the map 90 degrees. How can I do ? I use vue2-google-maps to create a map.

        <GmapMap
          id="map"
          :center="{lat:latitude, lng:longitude}"
          map-type-id="satellite"
          style="width: 100vw; height: 100vh"
          :zoom= zoom
          :tilt="rotate" // 45
          :options="{
            rotateControl: true,
            minZoom:5,
            maxZoom:20,
          }"
      />

Body:
According to documentation :

Once your map is displaying 45° imagery, you can orient the imagery
  towards one of its cardinal directions by calling setHeading() on the
  Map object, passing a number value expressed as degrees from North.

So, orient the imagery ( heading property) could be specified once 45° imagery is set, here is an example for vue-google-maps

<template>
  <div>
    <GmapMap
       :center="center"
      :zoom="zoom"
      :mapTypeId="'satellite'"
      :tilt="titl"
      :heading="heading"
       ref="map">

    </GmapMap>
  </div>
</template>

<script>
export default {
  data() {
    return {
      zoom: 18,
      center: { lat: 45.518, lng: -122.672 },
      titl: 45,
      heading: 90
    };
  },
  methods: {}
};
</script>


问:
Why data isn't updating after sorting in React Hooks?
I'm new to React Hooks. I'm trying to sort table inside React Hook, but after click my content doesn't update. Why is that?

This is my hook:

```<code>const Main = ({ dataProps }) => {
const [data, setData] = useState(dataProps);
const sortById = (field) => {
        let sortedData = data.sort((a, b) => {
            if(a[field] < b[field]) { return -1; }
            if(a[field] > b[field]) { return 1; }
            return 0;
        });
        setData(sortedData);
};
return (
        <table>
            <thead>
                <tr>
                    <th>iD <div className="arrows"><div onClick={() => sortById("id")} className="arrow-up"/></th>
                    <th>First name <div className="arrows"><div onClick={() => sortById("firstName")} className="arrow-up"/></div></th>
                </tr>
            </thead>
            <tbody>
            {data.map((user) => {
                return <tr key={user.id}>
                    <td className="number">{user.id}</td>
                    <td className="firstname">{user.firstName}</td>
                </tr>
            })}
            </tbody>
        </table>
);
};
</code>```

答:
sortById sorts the data array. But it does not trigger the component to rerender. The field here is obviously a state:

```<code> const [data, setData] = useState(dataProps);
 const [field, setField] = useState(null);

 const sorted = useMemo(() => {
   if(!field) return data;
   return data.slice().sort((a, b) => a[field].localeCompare(b[field]));
 }, [ data, field]);

 return <div>
   <a onClick={() => setField("firstName")}> Sort by Name</a>
   {sorted.map(/*...*/)}
</div>;
</code>```

Body:
I'm new to React Hooks. I'm trying to sort table inside React Hook, but after click my content doesn't update. Why is that?

This is my hook:

const Main = ({ dataProps }) => {
const [data, setData] = useState(dataProps);
const sortById = (field) => {
        let sortedData = data.sort((a, b) => {
            if(a[field]  b[field]) { return 1; }
            return 0;
        });
        setData(sortedData);
};
return (

                    iD

 sortById("id")} className="arrow-up"/>
                    First name

 sortById("firstName")} className="arrow-up"/>

            {data.map((user) => {
                return

                    {user.id}
                    {user.firstName}

            })}

);
};

Body:
sortById sorts the data array. But it does not trigger the component to rerender. The field here is obviously a state:

 const [data, setData] = useState(dataProps);
 const [field, setField] = useState(null);

 const sorted = useMemo(() => {
   if(!field) return data;
   return data.slice().sort((a, b) => a[field].localeCompare(b[field]));
 }, [ data, field]);

 return <div>
   <a onClick={() => setField("firstName")}> Sort by Name</a>
   {sorted.map(/*...*/)}
</div>;


问:
Highchart: Bubble heading is not showing if two bubbles intersect or comes near one another in Bubble chart
In Highcharts Bubblechart if i two bubbles comes near one another or intersect one another, the name on top of one bubble is not displaying.

Is there a way to display both the bubble names.

In this the notice the two bubbles in top right enter code herehttp://jsfiddle.net/htb38096/

答:
try this on dataLabels:

```<code>dataLabels: {
      enabled: true,
      useHTML: true,
      style: { textShadow: 'none',fontSize: '10px',color:'black' },
      formatter: function() {
             return this.point.name;
      },
}
</code>```

Body:
try this on dataLabels:

dataLabels: {
      enabled: true,
      useHTML: true,
      style: { textShadow: 'none',fontSize: '10px',color:'black' },
      formatter: function() {
             return this.point.name;
      },
}


问:
How to extract columns which contains lots of 0 value with R?
I have a matrix with lots of columns (more than 817.000) and 40 rows . I would like to extract the columns which contain lots of 0 (for example > 30 or 35 , no matter the number) .

That should extract several columns, and I will choose one randomnly which I will use as a reference for the rest of the matrix.

Any idea?

Edit :

```<code>              OTU0001 OTU0004 OTU0014 OTU0016 OTU0017 OTU0027 OTU0029 OTU0030
Sample_10.rare       0       0      85       0       0       0       0       0
Sample_11.rare       0      42     169       0      42     127       0      85
Sample_12.rare       0       0       0       0       0       0       0      42
Sample_13.rare     762     550    2159     127     550       0     677    1397
Sample_14.rare     847     508    2751     169    1397     169     593    1990
Sample_15.rare    1143     593    3725     677    2116     466     212    2286
Sample_16.rare    5630    5291    5291    1270    3852    1185     296    2836
</code>```

It should extract 4 columns, OTU0001 OTU0016  OTU0027 OTU0029 because they got 3 zero each. And if it is possible, I would like to extract the position of the extracted columns.

答:
An option with base R

```<code>Filter(function(x) sum(x == 0) > 7, df)
</code>```

Body:
I have a matrix with lots of columns (more than 817.000) and 40 rows . I would like to extract the columns which contain lots of 0 (for example > 30 or 35 , no matter the number) .

That should extract several columns, and I will choose one randomnly which I will use as a reference for the rest of the matrix.

Any idea?

Edit :

              OTU0001 OTU0004 OTU0014 OTU0016 OTU0017 OTU0027 OTU0029 OTU0030
Sample_10.rare       0       0      85       0       0       0       0       0
Sample_11.rare       0      42     169       0      42     127       0      85
Sample_12.rare       0       0       0       0       0       0       0      42
Sample_13.rare     762     550    2159     127     550       0     677    1397
Sample_14.rare     847     508    2751     169    1397     169     593    1990
Sample_15.rare    1143     593    3725     677    2116     466     212    2286
Sample_16.rare    5630    5291    5291    1270    3852    1185     296    2836

It should extract 4 columns, OTU0001 OTU0016  OTU0027 OTU0029 because they got 3 zero each. And if it is possible, I would like to extract the position of the extracted columns.

Body:
An option with base R

Filter(function(x) sum(x == 0) > 7, df)


问:
Add secondary x and y axis on ggplotly scatter plot
I have this data:

```<code>structure(list(ID = structure(c(3L, 4L, 4L, 4L, 4L, 4L, 1L, 5L,
2L, 2L), .Label = c("015753e0-8574-4b13-88d7-627292d52272", "2721a25c-cc0e-43d3-abd2-b29a0da8b9d0",
"60a7614a-63bb-4bb9-91ac-520549853c19", "86735a77-b822-4320-b16e-1ff2b5535f5d",
"8ff4d254-291b-47d4-970a-82f29f8a51fb"), class = "factor"), Impact = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 3L, 2L, 3L, 3L), .Label = c("Extreme impact",
"Moderate impact", "Strong impact"), class = "factor"), Size_bribe = structure(c(1L,
3L, 3L, 3L, 3L, 3L, 2L, 4L, 1L, 1L), .Label = c("10,000 Afs",
"100 Afs", "100,000 Afs", "No payment made"), class = "factor"),
    Abuse_type = structure(c(2L, 3L, 3L, 3L, 3L, 3L, 2L, 1L,
    2L, 2L), .Label = c("Delay of service", "Payment of money",
    "Threat of incarceration"), class = "factor"), service_worst_problem = structure(c(3L,
    1L, 1L, 1L, 1L, 1L, 2L, 4L, 3L, 3L), .Label = c("Obtaining a judgement",
    "Other", "Reporting a offence/crime to the police", "Vehicle registration"
    ), class = "factor"), Gender = structure(c(2L, 2L, 2L, 2L,
    2L, 2L, 2L, 1L, 2L, 2L), .Label = c("Female", "Male"), class = "factor"),
    Age = structure(c(3L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L), .Label = c("26 - 35",
    "36 - 45", "46 - 55"), class = "factor"), Education = structure(c(4L,
    2L, 2L, 2L, 2L, 2L, 1L, 3L, 1L, 1L), .Label = c("I do not have any formal education",
    "Primary education", "University or post-graduate education",
    "Vocational training after Secondary / High School"), class = "factor"),
    Madrassa = structure(c(1L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 1L,
    1L), .Label = c("No", "Yes, on a regular basis", "Yes, some"
    ), class = "factor"), Monthly_income = structure(c(2L, 1L,
    1L, 1L, 1L, 1L, 4L, 2L, 3L, 3L), .Label = c("20,001 - 25,000 AFN",
    "6001 - 8000 AFN", "8001 - 10,000 AFN", "Less than 2,000 AFN"
    ), class = "factor"), local_influence = structure(c(1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"),
    basis_local_influence = structure(c(1L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L), .Label = c("", "None of the above"), class = "factor"),
    current_occupation = structure(c(1L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L), .Label = c("Other", "Paid worker in any sector"
    ), class = "factor"), ethinic_group = structure(c(3L, 2L,
    2L, 2L, 2L, 2L, 1L, 3L, 3L, 3L), .Label = c("Aimaq", "Pashtun",
    "Tajik"), class = "factor"), location = structure(c(1L, 1L,
    1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L), .Label = c("Herat PD1 - Dawlat Khana",
    "Herat PD9 - Baghcha-e-Mastufi"), class = "factor"), City = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Herat", class = "factor"),
    NarrID = c(173L, 174L, 174L, 174L, 174L, 174L, 175L, 177L,
    178L, 178L), Stone.Num = c(1L, 1L, 2L, 3L, 4L, 5L, 4L, 1L,
    1L, 2L), NarrID_Stone = c(173.01, 174.01, 174.02, 174.03,
    174.04, 174.05, 175.04, 177.01, 178.01, 178.02), Stone.Name.L1 = structure(c(3L,
    3L, 4L, 1L, 5L, 2L, 5L, 3L, 3L, 4L), .Label = c("District Officials",
    "Malik / Wakil-e-Guzar", "Police", "Provincial Officials",
    "Religious Leaders"), class = "factor"), Canvas01.AdjXRightValue = c(0.7299,
    0.8994, 0.8615, 0.2399, 0.9103, NA, 0.8757, 0.0916, 0.1725,
    0.351), Canvas01.AdjYTopValue = c(0.2903, 0.8374, 0.6583,
    0.8183, 0.2167, NA, 0.8374, 0.7678, 0.705, 0.7239), Canvas01.Quadrant = structure(c(3L,
    4L, 4L, 2L, 3L, 1L, 4L, 2L, 2L, 2L), .Label = c("", "2.  Upper Left",
    "3.  Lower Right", "4.  Upper Right"), class = "factor"),
    Canvas02.AdjXRightValue = c(0.2113, 0.8892, 0.8102, 0.1629,
    0.8911, NA, 0.9206, 0.7614, 0.4365, 0.143), Canvas02.AdjYTopValue = c(0.2375,
    0.8305, 0.7514, 0.8385, 0.1948, NA, 0.2521, 0.8824, 0.5588,
    0.7078), Canvas02.Quadrant = structure(c(2L, 5L, 5L, 3L,
    4L, 1L, 4L, 5L, 3L, 3L), .Label = c("", "1. Lower Left",
    "2.  Upper Left", "3.  Lower Right", "4.  Upper Right"), class = "factor"),
    Canvas03.AdjXRightValue = c(0.2945, 0.8503, 0.7177, 0.2971,
    0.9026, NA, 0.1442, 0.6663, 0.1856, 0.6509), Canvas03.AdjYTopValue = c(0.2849,
    0.7296, 0.7228, 0.7445, 0.1675, NA, 0.836, 0.8469, 0.7808,
    0.8319), Canvas03.Quadrant = structure(c(2L, 5L, 5L, 3L,
    4L, 1L, 3L, 5L, 3L, 5L), .Label = c("", "1. Lower Left",
    "2.  Upper Left", "3.  Lower Right", "4.  Upper Right"), class = "factor"),
    Canvas04.AdjXRightValue = c(0.2804, 0.9165, 0.8147, 0.7183,
    0.1924, 0.6477, 0.6946, 0.0608, 0.1211, 0.3215), Canvas04.AdjYTopValue = c(0.2808,
    0.8114, 0.7282, 0.7064, 0.2767, 0.7391, 0.746, 0.3553, 0.615,
    0.6246), Canvas04.Quadrant = structure(c(1L, 3L, 3L, 3L,
    1L, 3L, 3L, 1L, 2L, 2L), .Label = c("1. Lower Left", "2.  Upper Left",
    "4.  Upper Right"), class = "factor"), Canvas05.AdjXRightValue = c(0.2817,
    0.2078, 0.2065, 0.1205, 0.2958, 0.1166, 0.1115, 0.1532, 0.2642,
    0.143), Canvas05.AdjYTopValue = c(0.2535, 0.2167, 0.3122,
    0.1455, 0.2399, 0.3094, 0.8169, 0.2789, 0.2883, 0.2453),
    Canvas05.Quadrant = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
    1L, 1L, 1L), .Label = c("1. Lower Left", "2.  Upper Left"
    ), class = "factor")), row.names = c(NA, 10L), class = "data.frame")
</code>```

and already has created this scatter plot using ggplotly():

```<code>ggplotly(
          ggplot(df_f, aes(x=Canvas01.AdjXRightValue, y=Canvas01.AdjYTopValue, colour=Gender)) +
          geom_point(aes(text=map(paste('<b>Canvas:</b>',"1 size and frequency",
                                        '<br>', '<b>Stone:</b>', Stone.Name.L1,
                                        '<br>', '<b>Quadrant:</b>', Canvas01.Quadrant,
                                        '<br>', '<b>About the Respondents Experience</b>'," ",
                                        '<br>', '<b>Impact:</b>', Impact,
                                        '<br>', '<b>Size of bribe:</b>', Size_bribe,
                                        '<br>', '<b>Type of abuse:</b>', Abuse_type,
                                        '<br>', '<b>Service with worst problem:</b>', service_worst_problem,
                                        '<br>', '<b>About the Respondent</b>'," ",
                                        '<br>', '<b>Gender:</b>', Gender,
                                        '<br>', '<b>Age:</b>', Age,
                                        '<br>', '<b>Education:</b>', Education,
                                        '<br>', '<b>Madrassa:</b>', Madrassa,
                                        '<br>', '<b>Monthly income:</b>', Monthly_income,
                                        '<br>', '<b>Local influence?:</b>', local_influence,
                                        '<br>', '<b>Basis of local influence:</b>', basis_local_influence,
                                        '<br>', '<b>Current occupation:</b>', current_occupation,
                                        '<br>', '<b>Ethnic group:</b>', ethinic_group,
                                        '<br>', '<b>Location:</b>', location,
                                        '<br>', '<b>Default text</b>'," "), HTML)))+
          xlab("Asked for small bribes or abused power minimally") +
          ylab("Asked for bribes or abused power infrequently") +
          ggtitle("1 size and frequency") + geom_hline(aes(yintercept=0.5),colour="black") +
            theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
                  panel.background = element_blank())+theme(legend.title = element_blank())+
          geom_vline(aes(xintercept=0.5), colour="black"))
</code>```

Everything works and looks fine, just that I need to add titles to the 4 sides of the chart, right now I have titles on the bottom and left side, but would like to add another title on top and right side.
How can I go about it?

Example of chart with the titles on all 4 sides:

答:
This is not a complete answer, as I cannot get it to work with plotly::ggplotly. I do hope it helps you one step further

Within a call to ggplot, you may use the sex.axis-argument in the scale_x_continuous() and scale_y_continuous() functions, like in the following code:

```<code>ggplot(df_f, aes(x = Canvas01.AdjXRightValue, y = Canvas01.AdjYTopValue, colour = Gender)) +
  geom_point() +
  xlab("Asked for small bribes or abused power minimally") +
  ylab("Asked for bribes or abused power infrequently") +
  ggtitle("1 size and frequency") +
  geom_hline(aes(yintercept=0.5),colour="black") +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank())+theme(legend.title = element_blank())+
  geom_vline(aes(xintercept=0.5), colour="black") +
  scale_x_continuous(sec.axis = dup_axis(name = "Asked for large bribes\nor abused power significantly")) +
  scale_y_continuous(sec.axis = dup_axis(name = "Asked for bribes or abused\n their power frequently"))
</code>```

yielding the following plot:

Body:
I have this data:

structure(list(ID = structure(c(3L, 4L, 4L, 4L, 4L, 4L, 1L, 5L,
2L, 2L), .Label = c("015753e0-8574-4b13-88d7-627292d52272", "2721a25c-cc0e-43d3-abd2-b29a0da8b9d0",
"60a7614a-63bb-4bb9-91ac-520549853c19", "86735a77-b822-4320-b16e-1ff2b5535f5d",
"8ff4d254-291b-47d4-970a-82f29f8a51fb"), class = "factor"), Impact = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 3L, 2L, 3L, 3L), .Label = c("Extreme impact",
"Moderate impact", "Strong impact"), class = "factor"), Size_bribe = structure(c(1L,
3L, 3L, 3L, 3L, 3L, 2L, 4L, 1L, 1L), .Label = c("10,000 Afs",
"100 Afs", "100,000 Afs", "No payment made"), class = "factor"),
    Abuse_type = structure(c(2L, 3L, 3L, 3L, 3L, 3L, 2L, 1L,
    2L, 2L), .Label = c("Delay of service", "Payment of money",
    "Threat of incarceration"), class = "factor"), service_worst_problem = structure(c(3L,
    1L, 1L, 1L, 1L, 1L, 2L, 4L, 3L, 3L), .Label = c("Obtaining a judgement",
    "Other", "Reporting a offence/crime to the police", "Vehicle registration"
    ), class = "factor"), Gender = structure(c(2L, 2L, 2L, 2L,
    2L, 2L, 2L, 1L, 2L, 2L), .Label = c("Female", "Male"), class = "factor"),
    Age = structure(c(3L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L), .Label = c("26 - 35",
    "36 - 45", "46 - 55"), class = "factor"), Education = structure(c(4L,
    2L, 2L, 2L, 2L, 2L, 1L, 3L, 1L, 1L), .Label = c("I do not have any formal education",
    "Primary education", "University or post-graduate education",
    "Vocational training after Secondary / High School"), class = "factor"),
    Madrassa = structure(c(1L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 1L,
    1L), .Label = c("No", "Yes, on a regular basis", "Yes, some"
    ), class = "factor"), Monthly_income = structure(c(2L, 1L,
    1L, 1L, 1L, 1L, 4L, 2L, 3L, 3L), .Label = c("20,001 - 25,000 AFN",
    "6001 - 8000 AFN", "8001 - 10,000 AFN", "Less than 2,000 AFN"
    ), class = "factor"), local_influence = structure(c(1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"),
    basis_local_influence = structure(c(1L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L), .Label = c("", "None of the above"), class = "factor"),
    current_occupation = structure(c(1L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L), .Label = c("Other", "Paid worker in any sector"
    ), class = "factor"), ethinic_group = structure(c(3L, 2L,
    2L, 2L, 2L, 2L, 1L, 3L, 3L, 3L), .Label = c("Aimaq", "Pashtun",
    "Tajik"), class = "factor"), location = structure(c(1L, 1L,
    1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L), .Label = c("Herat PD1 - Dawlat Khana",
    "Herat PD9 - Baghcha-e-Mastufi"), class = "factor"), City = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Herat", class = "factor"),
    NarrID = c(173L, 174L, 174L, 174L, 174L, 174L, 175L, 177L,
    178L, 178L), Stone.Num = c(1L, 1L, 2L, 3L, 4L, 5L, 4L, 1L,
    1L, 2L), NarrID_Stone = c(173.01, 174.01, 174.02, 174.03,
    174.04, 174.05, 175.04, 177.01, 178.01, 178.02), Stone.Name.L1 = structure(c(3L,
    3L, 4L, 1L, 5L, 2L, 5L, 3L, 3L, 4L), .Label = c("District Officials",
    "Malik / Wakil-e-Guzar", "Police", "Provincial Officials",
    "Religious Leaders"), class = "factor"), Canvas01.AdjXRightValue = c(0.7299,
    0.8994, 0.8615, 0.2399, 0.9103, NA, 0.8757, 0.0916, 0.1725,
    0.351), Canvas01.AdjYTopValue = c(0.2903, 0.8374, 0.6583,
    0.8183, 0.2167, NA, 0.8374, 0.7678, 0.705, 0.7239), Canvas01.Quadrant = structure(c(3L,
    4L, 4L, 2L, 3L, 1L, 4L, 2L, 2L, 2L), .Label = c("", "2.  Upper Left",
    "3.  Lower Right", "4.  Upper Right"), class = "factor"),
    Canvas02.AdjXRightValue = c(0.2113, 0.8892, 0.8102, 0.1629,
    0.8911, NA, 0.9206, 0.7614, 0.4365, 0.143), Canvas02.AdjYTopValue = c(0.2375,
    0.8305, 0.7514, 0.8385, 0.1948, NA, 0.2521, 0.8824, 0.5588,
    0.7078), Canvas02.Quadrant = structure(c(2L, 5L, 5L, 3L,
    4L, 1L, 4L, 5L, 3L, 3L), .Label = c("", "1. Lower Left",
    "2.  Upper Left", "3.  Lower Right", "4.  Upper Right"), class = "factor"),
    Canvas03.AdjXRightValue = c(0.2945, 0.8503, 0.7177, 0.2971,
    0.9026, NA, 0.1442, 0.6663, 0.1856, 0.6509), Canvas03.AdjYTopValue = c(0.2849,
    0.7296, 0.7228, 0.7445, 0.1675, NA, 0.836, 0.8469, 0.7808,
    0.8319), Canvas03.Quadrant = structure(c(2L, 5L, 5L, 3L,
    4L, 1L, 3L, 5L, 3L, 5L), .Label = c("", "1. Lower Left",
    "2.  Upper Left", "3.  Lower Right", "4.  Upper Right"), class = "factor"),
    Canvas04.AdjXRightValue = c(0.2804, 0.9165, 0.8147, 0.7183,
    0.1924, 0.6477, 0.6946, 0.0608, 0.1211, 0.3215), Canvas04.AdjYTopValue = c(0.2808,
    0.8114, 0.7282, 0.7064, 0.2767, 0.7391, 0.746, 0.3553, 0.615,
    0.6246), Canvas04.Quadrant = structure(c(1L, 3L, 3L, 3L,
    1L, 3L, 3L, 1L, 2L, 2L), .Label = c("1. Lower Left", "2.  Upper Left",
    "4.  Upper Right"), class = "factor"), Canvas05.AdjXRightValue = c(0.2817,
    0.2078, 0.2065, 0.1205, 0.2958, 0.1166, 0.1115, 0.1532, 0.2642,
    0.143), Canvas05.AdjYTopValue = c(0.2535, 0.2167, 0.3122,
    0.1455, 0.2399, 0.3094, 0.8169, 0.2789, 0.2883, 0.2453),
    Canvas05.Quadrant = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
    1L, 1L, 1L), .Label = c("1. Lower Left", "2.  Upper Left"
    ), class = "factor")), row.names = c(NA, 10L), class = "data.frame")

and already has created this scatter plot using ggplotly():

ggplotly(
          ggplot(df_f, aes(x=Canvas01.AdjXRightValue, y=Canvas01.AdjYTopValue, colour=Gender)) +
          geom_point(aes(text=map(paste('Canvas:',"1 size and frequency",
                                        '
', 'Stone:', Stone.Name.L1,
                                        '
', 'Quadrant:', Canvas01.Quadrant,
                                        '
', 'About the Respondents Experience'," ",
                                        '
', 'Impact:', Impact,
                                        '
', 'Size of bribe:', Size_bribe,
                                        '
', 'Type of abuse:', Abuse_type,
                                        '
', 'Service with worst problem:', service_worst_problem,
                                        '
', 'About the Respondent'," ",
                                        '
', 'Gender:', Gender,
                                        '
', 'Age:', Age,
                                        '
', 'Education:', Education,
                                        '
', 'Madrassa:', Madrassa,
                                        '
', 'Monthly income:', Monthly_income,
                                        '
', 'Local influence?:', local_influence,
                                        '
', 'Basis of local influence:', basis_local_influence,
                                        '
', 'Current occupation:', current_occupation,
                                        '
', 'Ethnic group:', ethinic_group,
                                        '
', 'Location:', location,
                                        '
', 'Default text'," "), HTML)))+
          xlab("Asked for small bribes or abused power minimally") +
          ylab("Asked for bribes or abused power infrequently") +
          ggtitle("1 size and frequency") + geom_hline(aes(yintercept=0.5),colour="black") +
            theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
                  panel.background = element_blank())+theme(legend.title = element_blank())+
          geom_vline(aes(xintercept=0.5), colour="black"))

Everything works and looks fine, just that I need to add titles to the 4 sides of the chart, right now I have titles on the bottom and left side, but would like to add another title on top and right side.
How can I go about it?

Example of chart with the titles on all 4 sides:

Body:
This is not a complete answer, as I cannot get it to work with plotly::ggplotly. I do hope it helps you one step further

Within a call to ggplot, you may use the sex.axis-argument in the scale_x_continuous() and scale_y_continuous() functions, like in the following code:

ggplot(df_f, aes(x = Canvas01.AdjXRightValue, y = Canvas01.AdjYTopValue, colour = Gender)) +
  geom_point() +
  xlab("Asked for small bribes or abused power minimally") +
  ylab("Asked for bribes or abused power infrequently") +
  ggtitle("1 size and frequency") +
  geom_hline(aes(yintercept=0.5),colour="black") +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank())+theme(legend.title = element_blank())+
  geom_vline(aes(xintercept=0.5), colour="black") +
  scale_x_continuous(sec.axis = dup_axis(name = "Asked for large bribes\nor abused power significantly")) +
  scale_y_continuous(sec.axis = dup_axis(name = "Asked for bribes or abused\n their power frequently"))

yielding the following plot:


问:
Java For each loop every instance from class
I start with OOP
And i have following problem:
I made a new class
Then I made ainstance from this class
Now, for every instance I want to do something
I tried it with a for each loop but it doesn't work...
There are some syntax problems

This is the class:

package main;

public class command
{
    String call;
    String execute;
}
```

<p>And this from the Main class:</p>

<pre class="lang-java prettyprint-override"><code> private static void load() {
        command greeting = new command();

        greeting.call = "hello";
        greeting.execute = "Hello Sir";

        for (command c: command) {
            System.out.println("Another command...");
        }

    }
</code>```

I don't know how to make the loop or is there another way to do it?

答:
You can create a static list inside class command that the instances get added to in the constructor(s).  Then you'll always have references to whatever instances are created.

Here's an example:

```<code>import java.util.List;
import java.util.ArrayList;
public class command
{

    String call;
    String execute;

    public static List<command> commands = new ArrayList<>();

    public command() {
        commands.add(this);
    }

    public command(String call, String execute)
    {
        this.call = call;
        this.execute = execute;
        commands.add(this);
    }

    public String toString()
    {
        return "call: " + call + " | execute: " + execute;
    }

}
</code>```

Driver class:

```<code>public class driver
{
    public static void main(String[] args)
    {
        for(int i = 1; i <=10; i++)
        {
            command c = new command("call" + i, "execute" + i);
        }

        for(command cmd: command.commands)
        {
            System.out.println(cmd);
        }
    }
}
</code>```

Output:

Body:
I start with OOP
And i have following problem:
I made a new class
Then I made ainstance from this class
Now, for every instance I want to do something
I tried it with a for each loop but it doesn't work...
There are some syntax problems

This is the class:

package main;

public class command
{
    String call;
    String execute;
}

And this from the Main class:

 private static void load() {
        command greeting = new command();

        greeting.call = "hello";
        greeting.execute = "Hello Sir";

        for (command c: command) {
            System.out.println("Another command...");
        }

    }

I don't know how to make the loop or is there another way to do it?

Body:
You can create a static list inside class command that the instances get added to in the constructor(s).  Then you'll always have references to whatever instances are created.

Here's an example:

import java.util.List;
import java.util.ArrayList;
public class command
{

    String call;
    String execute;

    public static List<command> commands = new ArrayList<>();

    public command() {
        commands.add(this);
    }

    public command(String call, String execute)
    {
        this.call = call;
        this.execute = execute;
        commands.add(this);
    }

    public String toString()
    {
        return "call: " + call + " | execute: " + execute;
    }

}

Driver class:

public class driver
{
    public static void main(String[] args)
    {
        for(int i = 1; i <=10; i++)
        {
            command c = new command("call" + i, "execute" + i);
        }

        for(command cmd: command.commands)
        {
            System.out.println(cmd);
        }
    }
}

Output:


问:
how return to top button works
I have looked around many places  return to top  button .when i click on that that takes me to top of the page.

some time some links taking me to particular place how does this works

is this html tack ticks or javascript..can i do this without page loading ?

答:
If you require to jump to a particular portion of the page by default during page than read on:
Just append the id of the tag with URL.
Eg:

Some content

Now if your URL ends with #myID than it shall jump to that portion automatically.

Title: how return to top button works

Body:
If you require to jump to a particular portion of the page by default during page than read on:
Just append the id of the tag with URL.
Eg:
   <div id='myID'>Some content</div>

Now if your URL ends with #myID than it shall jump to that portion automatically.


问:
Custom date range inline picker
Framework which I use (Angular 7) and ngx-bootstrap ^4.0.0

I want  to  make inline daterangepicker.

Package ngx-bootstrap have inline  datepicker (bs-datepicker-inline) and directive (bsDaterangepicker) for classic dialog daterangepicker.

I try use attribute container for  create daterangepicker in element wth relative position, but after select date is component closed. When i use hide event call method show, it's working but with 'blink'.

Do you have any experience with it?

Here is example.

答:
I think what you're looking for is something that they actually have it in their documentation here.

You can check this Sample StackBlitz out for the implementation.

Title: Custom date range inline picker


问:
dictionary/map/key-value pairs data structure in C
How does one construct and access a set of key-value pairs in C? To use a silly simple example, let's say I want to create a table which translates between an integer and its square root.

If I were writing javascript, I could just do this:

```<code>var squareRoots = {
   4: 2,
   9: 3,
   16: 4,
   25: 5
}
</code>```

and then access them like:

```<code>var squareRootOf25 = squareRoots[5]
</code>```

How do I do this in C? What if I want to use one type of enum as the key and another type of enum as the value?

答: You can use map implemented as part of clib library</p>

Body:
How does one construct and access a set of key-value pairs in C? To use a silly simple example, let's say I want to create a table which translates between an integer and its square root.

If I were writing javascript, I could just do this:

var squareRoots = {
   4: 2,
   9: 3,
   16: 4,
   25: 5
}

and then access them like:

var squareRootOf25 = squareRoots[5]

How do I do this in C? What if I want to use one type of enum as the key and another type of enum as the value?


问:
Read file in SSIS Project into a variable
My SSIS projects tend to run queries that require changes as they move between environments, like the table schema might change or a value in the Where clause.  I've always either put my SQL into a Project Parameter, which is hard to edit since formatting is lost, or just put it directly into the Execute SQL Task/Data Flow Source then manually edited it between migrations which is also not ideal.

I was wonder though if I added my SQL scripts to files within the project, can these be read back in?  Example if I put a query like this:
select id, name from %schema%.tablename
I'd like to read this into a variable then it's easy to use an expression as I do with Project Parameters to replace %schema% with the appropriate value.  Then the .sql files within the project can be edited with little effort or even tested through an Execute SQL Task that's disabled/removed before the project goes into the deployment flow. But I've been unable to find how to read in a file using a relative path within the project.  Also I'm not even sure these get deployed to the SSIS Server.

Thanks for any insight.

I've added a text file query.sql to an SSIS (SQL 2017) Project in Visual Studio, bit I've found no way to pull the contents of query.sql into a variable.

答:
You can build your query by using both Variable and Parameter.

For example:

Parameter A: dbo

Build your variable A (string type) as : "Select * FROM server.DB." + ParameterA + ".Table"

So if you need to change the schema, just change the parameter A will give you the corresponding query in variable A.


问:
Display output of MySQL query in one line/ horizontally
I am validating the results of a MySQL database that I created and, for that, I need some screenshots.

For example, the following query:

```<code>select distinct run_ID
from ngsRunStats_FK.failedRuns
where reason_fail regexp 'cannot populate readsInfo'
</code>```

will return (output from the terminal)

But as we can see, the screenshot is quite too long.

Is there a way to, instead of display the output as a (vertical) column, to display only its values horizontally (e.g. like in a python list)?

答:
Try using GROUP_CONCAT:

```<code>SELECT GROUP_CONCAT(run_ID ORDER BY run_ID) AS run_ID_values
FROM ngsRunStats_FK.failedRuns
WHERE reason_fail REGEXP 'cannot populate readsInfo';
</code>```

Side note:

If you really want to match the three keywords cannot populate readsInfo anywhere inside a larger text within the reason_fail column, then consider using word boundaries with REGEXP:

```<code>WHERE reason_fail REGEXP '[[:<:]]cannot populate readsInfo[[:>:]]';
</code>```

Body:
I am validating the results of a MySQL database that I created and, for that, I need some screenshots.

For example, the following query:

select distinct run_ID
from ngsRunStats_FK.failedRuns
where reason_fail regexp 'cannot populate readsInfo'

will return (output from the terminal)

But as we can see, the screenshot is quite too long.

Is there a way to, instead of display the output as a (vertical) column, to display only its values horizontally (e.g. like in a python list)?

Body:
Try using GROUP_CONCAT:

SELECT GROUP_CONCAT(run_ID ORDER BY run_ID) AS run_ID_values
FROM ngsRunStats_FK.failedRuns
WHERE reason_fail REGEXP 'cannot populate readsInfo';

Side note:

If you really want to match the three keywords cannot populate readsInfo anywhere inside a larger text within the reason_fail column, then consider using word boundaries with REGEXP:

WHERE reason_fail REGEXP '[[:<:]]cannot populate readsInfo[[:>:]]';


问:
Add class to parent div that matches label text
I would like to add a class to each parent div and have that class match the content of the label within the div with a hyphen added between each word.

In the example below, the first div would have class child-1-name, the second child-1-last-name, the third child-1-age. Any direction would be greatly appreciated!

Note that the HTML is generated automatically.

    child 1 name
    <input type="text">

    child 1 last name
    <input type="text">

    child 1 age
    <input type="text">

```

答:
Here's a pretty simple way to do it: just find the text, remove whitespace on the outside, convert to lowercase, and replace all other whitespace with dashes.

$(".wrapable").each(function(i, el) {
  var className = el.innerText.trim().toLowerCase().replace(/\s+/g, '-');
  $(el).closest('div').addClass(className);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.child-1-name {background: pink;}
.child-1-last-name { background: lightgreen;}
.child-1-age {background: lightblue;}</code>```

    child 1 name
    <input type="text">

    child 1 last name
    <input type="text">

    child 1 age
    <input type="text">

```

Body:
Here's a pretty simple way to do it: just find the text, remove whitespace on the outside, convert to lowercase, and replace all other whitespace with dashes.

$(".wrapable").each(function(i, el) {
  var className = el.innerText.trim().toLowerCase().replace(/\s+/g, '-');
  $(el).closest('div').addClass(className);
});

.child-1-name {background: pink;}
.child-1-last-name { background: lightgreen;}
.child-1-age {background: lightblue;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"></span>
  </span>
</div>


问:
Vim and Ctags tips and tricks
I have just installed Ctags (to help with C++ development) with my Vim (or rather gVim), and would like to find out your favorite commands, macros, shortcuts, tips that go along with it...

Share your best arsenal. What other Vim add-ons you would recommend for C++ on Vim development?

EDIT What other add-on you would use in conjunction with Ctags?

EDIT2 What version of gVim you use with tags? Does it make a difference?

EDIT3 How do you enhance your programming experience for both big and small projects?

答:
You can add directories to your ctags lookup.  For example, I have a ctags index built for Qt4, and have this in my .vimrc:</p>

```<code>set tags+=/usr/local/share/ctags/qt4
</code>```

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

ContentLicense: CC BY-SA 2.5

Title: Vim and Ctags tips and tricks

Body:
You can add directories to your ctags lookup.  For example, I have a ctags index built for Qt4, and have this in my .vimrc:

set tags+=/usr/local/share/ctags/qt4

OwnerDisplayName: strager


问:
Placing generated elements into correct divs from Object based on property written in object by jQuery
There is an object. Order, block and Position has been written for the object element like this way:

```<code>var formObj = {
  username: {
    value: null,
    type: 'text',
    label: 'Username',
    placeholder: 'Enter username',
    position: 'left',
    block: 'firstRow',
    order: 1,
    additionalClass: 'user'
  },
  message: {
    value: null,
    type: 'textarea',
    label: 'Message',
    placeholder: 'type your message',
    position: 'left',
    block: 'secondRow',
    order: 3,
  },
}
</code>```

Inputs are generating from the object and stored in variable named html:

```<code>var html = '';
$.each(formObj, function(key, value) {
   var html = '';
   html += '<input name="' + key + '" type="' + value.type + '" value="' + value.value + '" placeholder="' + value.placeholder + '"' + classMarkup + addedAttrs + '/>';
return html;
})
</code>```

In my html, there are two rows named first-row and second-row. Each row has two columns: left-col and right-col.

Generated input elements will need to be placed based on the block, position & order. So, if a object has order: 2, position: 'left', block: 'firstRow' and another object has order: 1, position: 'left', block: 'firstRow', then both of the object goes under div.first-row and div.left-col and second object goes to first order and first object goes to second order. I have tried to generate that like this way:

```<code>var firstLeft = [],
    firstRight = [],
    secondLeft = [],
    secondRight = [];
function columnPosition(row, column) {
    if (row === 'firstRow' && column === 'left') {
       firstLeft.push(html);
       $('.first-row .left-col').append(firstLeft);
  } else if (row === 'firstRow' && column === 'right') {

  } else if (row === 'secondRow' && column === 'left') {

  } else if (row === 'secondRow' && column === 'left') {

  }

}
// sort by order function
function sortByOrder (array,key) {
    return array.sort(function (a, b) {
    var x = a[key];
    var y = b[key];
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
</code>```

But, I cannot write this function properly. How to achieve this functionality?

Fiddle Demo

答:
I didn't reuse all your fiddle, I just took what you gave us as example.

You made complicated when you can do easier:

Use an array instead of an object, it's easier to sort it. Here, I wrote a function to switch to a sorted array with a for...in statement.

Then I iterated through each form object with Array#forEach. I created the corresponding element at each iteration in function the field's type (I didn't your own functions, but use it when you'll adapt my code snippet). Finally, I found the right place to append the created element with jQuery#find.

const formObj = {
  username: {
    value: null,
    type: 'text',
    label: 'Username',
    placeholder: 'Enter username',
    position: 'left',
    block: 'firstRow',
    order: 1,
    additionalClass: 'user'
  },
  password: {
    value: null,
    type: 'password',
    label: 'Password',
    placeholder: 'enter password',
    position: 'left',
    block: 'firstRow',
    order: 2
  },
  country: {
    value: null,
    type: 'select',
    label: 'Where are you form?',
    defaultText: 'Choose here',
    position: 'right',
    block: 'firstRow',
    order: 2,
    option: [{
        value: '1',
        label: 'Australia'
      },
      {
        value: '2',
        label: 'USA'
      },
      {
        value: '3',
        label: 'UK'
      }
    ]
  },
  gender: {
    value: 'other',
    type: 'select',
    label: 'Gender',
    defaultText: null,
    position: 'right',
    block: 'firstRow',
    order: 1,
    option: [{
        value: 'male',
        label: 'Male'
      },
      {
        value: 'female',
        label: 'Female'
      },
      {
        value: 'other',
        label: 'Other',
        additionalAttr: 'disabled'
      }
    ]
  },
  decision: {
    value: 'not sure',
    type: 'radio',
    label: 'Have you enjoyed it?',
    position: 'left',
    block: 'secondRow',
    order: 1,
    option: [{
        value: 'yes',
        label: 'Yes',
        additionalAttr: 'disabled'
      },
      {
        value: 'no',
        label: 'No',
      },
      {
        value: 'not sure',
        label: 'I am not sure',
      }
    ]
  },
  message: {
    value: null,
    type: 'textarea',
    label: 'Message',
    placeholder: 'type your message',
    position: 'left',
    block: 'secondRow',
    order: 3,
  },
  vehicle: {
    value: null,
    type: 'checkbox',
    label: 'Preferred vehicles',
    position: 'left',
    block: 'secondRow',
    order: 2,
    option: [{
        value: 'car',
        label: 'I like car'
      },
      {
        value: 'bike',
        label: 'I prefer bike'
      },
      {
        value: 'boat',
        label: 'Boat is my favorit'
      }
    ]
  },
  email: {
    value: null,
    type: 'text',
    label: 'Email',
    placeholder: 'Enter email',
    position: 'right',
    block: 'secondRow',
    order: 2,
    additionalAttr: 'disabled',
    additionalClass: 'emailbox custom'
  }
};

fieldListObjectToArray(formObj).forEach((field) => {
  const jForm = $('.form'),
    jElement = createElement(field);

  // Appends the newly created element to the right place.
  jForm
    .find(`.${field.block.replace('Row', '-row')}`)
    .find(`.${field.position}-col`)
    .append(jElement);
});

/**
 * Transforms your form object into an array one for easier usage.
 */
function fieldListObjectToArray(fieldObj) {
  let fieldArr = [];

  for (let key in fieldObj) {
    const field = fieldObj[key];

    // Adds to the array the original object with more one key "id" (= to the object key).
    fieldArr.push({
      id: key,
      ...field
    });

    // Sorts in ASC order.
    fieldArr.sort((a, b) => (a.order - b.order));
  }

  return fieldArr;
}

/**
 * Creates an element in function of the given {field}'s type.
 */
function createElement(field) {
  let jElement;

  switch (field.type) {
    case 'select':
      jElement = createSelectElement(field);
      break;

    case 'textarea':
      jElement = createTextareaElement(field);
      break;

    case 'radio':
    case 'checkbox':
      jElement = createCheckboxRadioElement(field);
      break;

    default:
      jElement = createInputElement(field);
  }

  if(!['checkbox', 'radio'].includes(field.type)) {
    jElement.addClass(field.additionalClass || '');
  }

  if (field.additionalAttr) {
    for (let attr of field.additionalAttr.split(' ')) {
      jElement.attr(attr, attr);
    }
  }

  return $('').text(field.label).append(jElement);
}

/**
 * Creates an <input> element from object.
 */
function createInputElement(field) {
  return $('<input>')
    .attr('type', field.type)
    .attr('name', field.id)
    .attr('placeholder', field.placeholder)
    .val(field.value);
}

/**
 * Creates an <input type="checkbox/radio"> element from object.
 */
function createCheckboxRadioElement(field) {
  const jElements = [];

  // Inputs.
  for (let option of field.option) {
    const jElement = $('<input>')
      .attr('type', field.type)
      .attr('name', field.id)
      .val(option.value);

    if (field.type === 'checkbox') {
      jElement.attr('name', `${field.id}[]`);
    }

    if (option.additionalAttr) {
      for (let attr of option.additionalAttr.split(' ')) {
        jElement.attr(attr, attr);
      }
    }

    if (field.value === option.value) {
      jElement.prop('checked', true);
    }

    jElements.push($('').text(option.label).prepend(jElement));
  }

  return jElements;
}

/**
 * Creates a <textarea> element from object.
 */
function createTextareaElement(field) {
  return $('<textarea>')
    .attr('name', field.id)
    .attr('placeholder', field.placeholder)
    .val(field.value);
}

/**
 * Creates a <select> element from object.
 */
function createSelectElement(field) {
  const jElement = $('<select>')
    .attr('name', field.id);

  // Default option.
  if (field.defaultText) {
    $('<option>')
      .text(field.defaultText)
      .prop('selected', true)
      .prop('disabled', true)
      .appendTo(jElement);
  }

  // Options.
  for (let option of field.option) {
    const jOption = $('<option>')
      .val(option.value)
      .text(option.label);

    if (option.additionalAttr) {
      for (let attr of option.additionalAttr.split(' ')) {
        jOption.attr(attr, attr);
      }
    }

    if (field.value === option.value) {
      jOption.prop('selected', true);
    }

    jOption.appendTo(jElement);
  }

  return jElement;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.second-row {
  border-top: 1px solid #aaa;
  margin-top: 50px;
  padding-top: 30px;
}

button {
  margin-top: 30px;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Form

  <form class="form">

Left Column

right Column

Left Column

right Column

    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

```

Body:
There is an object. Order, block and Position has been written for the object element like this way:

var formObj = {
  username: {
    value: null,
    type: 'text',
    label: 'Username',
    placeholder: 'Enter username',
    position: 'left',
    block: 'firstRow',
    order: 1,
    additionalClass: 'user'
  },
  message: {
    value: null,
    type: 'textarea',
    label: 'Message',
    placeholder: 'type your message',
    position: 'left',
    block: 'secondRow',
    order: 3,
  },
}

Inputs are generating from the object and stored in variable named html:

var html = '';
$.each(formObj, function(key, value) {
   var html = '';
   html += '<input name="' + key + '" type="' + value.type + '" value="' + value.value + '" placeholder="' + value.placeholder + '"' + classMarkup + addedAttrs + '/>';
return html;
})

In my html, there are two rows named first-row and second-row. Each row has two columns: left-col and right-col.

Generated input elements will need to be placed based on the block, position & order. So, if a object has order: 2, position: 'left', block: 'firstRow' and another object has order: 1, position: 'left', block: 'firstRow', then both of the object goes under div.first-row and div.left-col and second object goes to first order and first object goes to second order. I have tried to generate that like this way:

var firstLeft = [],
    firstRight = [],
    secondLeft = [],
    secondRight = [];
function columnPosition(row, column) {
    if (row === 'firstRow' && column === 'left') {
       firstLeft.push(html);
       $('.first-row .left-col').append(firstLeft);
  } else if (row === 'firstRow' && column === 'right') {

  } else if (row === 'secondRow' && column === 'left') {

  } else if (row === 'secondRow' && column === 'left') {

  }

}
// sort by order function
function sortByOrder (array,key) {
    return array.sort(function (a, b) {
    var x = a[key];
    var y = b[key];
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}

But, I cannot write this function properly. How to achieve this functionality?

Fiddle Demo

Body:
I didn't reuse all your fiddle, I just took what you gave us as example.

You made complicated when you can do easier:

Use an array instead of an object, it's easier to sort it. Here, I wrote a function to switch to a sorted array with a for...in statement.

Then I iterated through each form object with Array#forEach. I created the corresponding element at each iteration in function the field's type (I didn't your own functions, but use it when you'll adapt my code snippet). Finally, I found the right place to append the created element with jQuery#find.

const formObj = {
  username: {
    value: null,
    type: 'text',
    label: 'Username',
    placeholder: 'Enter username',
    position: 'left',
    block: 'firstRow',
    order: 1,
    additionalClass: 'user'
  },
  password: {
    value: null,
    type: 'password',
    label: 'Password',
    placeholder: 'enter password',
    position: 'left',
    block: 'firstRow',
    order: 2
  },
  country: {
    value: null,
    type: 'select',
    label: 'Where are you form?',
    defaultText: 'Choose here',
    position: 'right',
    block: 'firstRow',
    order: 2,
    option: [{
        value: '1',
        label: 'Australia'
      },
      {
        value: '2',
        label: 'USA'
      },
      {
        value: '3',
        label: 'UK'
      }
    ]
  },
  gender: {
    value: 'other',
    type: 'select',
    label: 'Gender',
    defaultText: null,
    position: 'right',
    block: 'firstRow',
    order: 1,
    option: [{
        value: 'male',
        label: 'Male'
      },
      {
        value: 'female',
        label: 'Female'
      },
      {
        value: 'other',
        label: 'Other',
        additionalAttr: 'disabled'
      }
    ]
  },
  decision: {
    value: 'not sure',
    type: 'radio',
    label: 'Have you enjoyed it?',
    position: 'left',
    block: 'secondRow',
    order: 1,
    option: [{
        value: 'yes',
        label: 'Yes',
        additionalAttr: 'disabled'
      },
      {
        value: 'no',
        label: 'No',
      },
      {
        value: 'not sure',
        label: 'I am not sure',
      }
    ]
  },
  message: {
    value: null,
    type: 'textarea',
    label: 'Message',
    placeholder: 'type your message',
    position: 'left',
    block: 'secondRow',
    order: 3,
  },
  vehicle: {
    value: null,
    type: 'checkbox',
    label: 'Preferred vehicles',
    position: 'left',
    block: 'secondRow',
    order: 2,
    option: [{
        value: 'car',
        label: 'I like car'
      },
      {
        value: 'bike',
        label: 'I prefer bike'
      },
      {
        value: 'boat',
        label: 'Boat is my favorit'
      }
    ]
  },
  email: {
    value: null,
    type: 'text',
    label: 'Email',
    placeholder: 'Enter email',
    position: 'right',
    block: 'secondRow',
    order: 2,
    additionalAttr: 'disabled',
    additionalClass: 'emailbox custom'
  }
};

fieldListObjectToArray(formObj).forEach((field) => {
  const jForm = $('.form'),
    jElement = createElement(field);

  // Appends the newly created element to the right place.
  jForm
    .find(`.${field.block.replace('Row', '-row')}`)
    .find(`.${field.position}-col`)
    .append(jElement);
});

/**
 * Transforms your form object into an array one for easier usage.
 */
function fieldListObjectToArray(fieldObj) {
  let fieldArr = [];

  for (let key in fieldObj) {
    const field = fieldObj[key];

    // Adds to the array the original object with more one key "id" (= to the object key).
    fieldArr.push({
      id: key,
      ...field
    });

    // Sorts in ASC order.
    fieldArr.sort((a, b) => (a.order - b.order));
  }

  return fieldArr;
}

/**
 * Creates an element in function of the given {field}'s type.
 */
function createElement(field) {
  let jElement;

  switch (field.type) {
    case 'select':
      jElement = createSelectElement(field);
      break;

    case 'textarea':
      jElement = createTextareaElement(field);
      break;

    case 'radio':
    case 'checkbox':
      jElement = createCheckboxRadioElement(field);
      break;

    default:
      jElement = createInputElement(field);
  }

  if(!['checkbox', 'radio'].includes(field.type)) {
    jElement.addClass(field.additionalClass || '');
  }

  if (field.additionalAttr) {
    for (let attr of field.additionalAttr.split(' ')) {
      jElement.attr(attr, attr);
    }
  }

  return $('<label>').text(field.label).append(jElement);
}

/**
 * Creates an <input> element from object.
 */
function createInputElement(field) {
  return $('<input>')
    .attr('type', field.type)
    .attr('name', field.id)
    .attr('placeholder', field.placeholder)
    .val(field.value);
}

/**
 * Creates an <input type="checkbox/radio"> element from object.
 */
function createCheckboxRadioElement(field) {
  const jElements = [];

  // Inputs.
  for (let option of field.option) {
    const jElement = $('<input>')
      .attr('type', field.type)
      .attr('name', field.id)
      .val(option.value);

    if (field.type === 'checkbox') {
      jElement.attr('name', `${field.id}[]`);
    }

    if (option.additionalAttr) {
      for (let attr of option.additionalAttr.split(' ')) {
        jElement.attr(attr, attr);
      }
    }

    if (field.value === option.value) {
      jElement.prop('checked', true);
    }

    jElements.push($('<span>').text(option.label).prepend(jElement));
  }

  return jElements;
}

/**
 * Creates a <textarea> element from object.
 */
function createTextareaElement(field) {
  return $('<textarea>')
    .attr('name', field.id)
    .attr('placeholder', field.placeholder)
    .val(field.value);
}

/**
 * Creates a <select> element from object.
 */
function createSelectElement(field) {
  const jElement = $('<select>')
    .attr('name', field.id);

  // Default option.
  if (field.defaultText) {
    $('<option>')
      .text(field.defaultText)
      .prop('selected', true)
      .prop('disabled', true)
      .appendTo(jElement);
  }

  // Options.
  for (let option of field.option) {
    const jOption = $('<option>')
      .val(option.value)
      .text(option.label);

    if (option.additionalAttr) {
      for (let attr of option.additionalAttr.split(' ')) {
        jOption.attr(attr, attr);
      }
    }

    if (field.value === option.value) {
      jOption.prop('selected', true);
    }

    jOption.appendTo(jElement);
  }

  return jElement;
}

.second-row {
  border-top: 1px solid #aaa;
  margin-top: 50px;
  padding-top: 30px;
}

button {
  margin-top: 30px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
  <h2>Form</h2>
  <form class="form">
    <div class="row first-row">
      <div class="col-sm-6">
        <div class="left-col">
          <h4>Left Column</h4>
        </div>
      </div>
      <div class="col-sm-6">
        <div class="right-col">
          <h4>right Column</h4>
        </div>
      </div>
    </div>

    <div class="row second-row">
      <div class="col-sm-6">
        <div class="left-col">
          <h4>Left Column</h4>
        </div>
      </div>
      <div class="col-sm-6">
        <div class="right-col">
          <h4>right Column</h4>
        </div>
      </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</div>


问:
How to POST to Slim framework with AJAX?
I'm using slim framework with eloquent to talk to the db. I'm trying to make a simple post ajax request that posts the data to db.
so I have this route:

```<code>//post yell
$app->post('/yell', 'UserController:postYell')->setName('yell');
</code>```

which is resolved by this controller

```<code>public function postYell($request, $response)
{
$yell = Yell::create([
  'body' => $request->getParam('yellBody'),
  'user_id' => $_SESSION['user'],
]);

return $response->withRedirect($_SERVER['HTTP_REFERER']);
}
</code>```

I tried something like this:

```<code>$(".postYell").submit(function(){
    $.ajax(
    {
        url: "/yell",
        type: 'POST',
        data: {
            "_method": 'POST',
        },
        success: function ()
        {
            console.log("it Work");
        }
    });

    console.log("It failed");
});
</code>```

but I don't think this is the right way to do this. I'm still pretty new to this so pardon me if I'm missing something obvious. I can't find a good example of how to ajax stuff with slim, and I've been stuck on how to do this for a few hours now, so I'd greatly appreciate it if someone could point me in the right direction

答:
As per Slim3 documentation

```<code>if ($request->isXhr()) {
        return $response;
    }
</code>```

is a great way to ascertain if the request was from a JQuery AJAX call

vote up

Body:
I'm using slim framework with eloquent to talk to the db. I'm trying to make a simple post ajax request that posts the data to db.
so I have this route:

//post yell
$app->post('/yell', 'UserController:postYell')->setName('yell');

which is resolved by this controller

public function postYell($request, $response)
{
$yell = Yell::create([
  'body' => $request->getParam('yellBody'),
  'user_id' => $_SESSION['user'],
]);

return $response->withRedirect($_SERVER['HTTP_REFERER']);
}

I tried something like this:

$(".postYell").submit(function(){
    $.ajax(
    {
        url: "/yell",
        type: 'POST',
        data: {
            "_method": 'POST',
        },
        success: function ()
        {
            console.log("it Work");
        }
    });

    console.log("It failed");
});

but I don't think this is the right way to do this. I'm still pretty new to this so pardon me if I'm missing something obvious. I can't find a good example of how to ajax stuff with slim, and I've been stuck on how to do this for a few hours now, so I'd greatly appreciate it if someone could point me in the right direction

Body:
As per Slim3 documentation

if ($request->isXhr()) {
        return $response;
    }

is a great way to ascertain if the request was from a JQuery AJAX call

vote up


问:
Accessing Vue.$router inside an external "service" class
I have a service which extends EventEmitter.

services/service/service.js (relative to main.js)

```<code>import { EventEmitter } from "events";

class Service extends EventEmitter {}
</code>```

Inside the Service class, I have the following method which returns a Promise:

```<code>  /**
   * Method to fetch the Active Survey by "surveySlug":
   */
  fetchActiveSurvey(serviceSlug) {
    return new Promise((resolve, reject) => {
      axios.get(`${this.baseURL}/service/${serviceSlug}`, { headers: { Authorization: AuthStr } }).then(response => {
        resolve(response.data);
      }).catch(error => {
        if (error.response && error.response.data.status != 200) {
          Vue.$router.push({ name: 'home'});
        }
      });
    });
  }

</code>```

I also have the usual routes.js in the same directory as main.js, which is working fine.

Services are then established as plugins:

```<code>import Service from "../services/service/service"; // <= Refrences `service.js`

export default {
  install(Vue) {
    Vue.prototype.$service = Service;
  }
};
</code>```

I have tried the following:

Vue.$router.push({ name: 'home'});

Vue.prototype.$router.push({ name: 'home'});

However, I seem to find that $router is not defined. What would be the best way to define the router push routes from inside this service?

答:
You need to use the this keyword to access the router instance. Try:

```<code>this.$router.push({ name: 'home'});
</code>```

Body:
I have a service which extends EventEmitter.

services/service/service.js (relative to main.js)

import { EventEmitter } from "events";

class Service extends EventEmitter {}

Inside the Service class, I have the following method which returns a Promise:

  /**
   * Method to fetch the Active Survey by "surveySlug":
   */
  fetchActiveSurvey(serviceSlug) {
    return new Promise((resolve, reject) => {
      axios.get(`${this.baseURL}/service/${serviceSlug}`, { headers: { Authorization: AuthStr } }).then(response => {
        resolve(response.data);
      }).catch(error => {
        if (error.response && error.response.data.status != 200) {
          Vue.$router.push({ name: 'home'});
        }
      });
    });
  }

I also have the usual routes.js in the same directory as main.js, which is working fine.

Services are then established as plugins:

import Service from "../services/service/service"; // <= Refrences `service.js`

export default {
  install(Vue) {
    Vue.prototype.$service = Service;
  }
};

I have tried the following:

Vue.$router.push({ name: 'home'});

Vue.prototype.$router.push({ name: 'home'});

However, I seem to find that $router is not defined. What would be the best way to define the router push routes from inside this service?

Body:
You need to use the this keyword to access the router instance. Try:

this.$router.push({ name: 'home'});