问:
new username is created instead of getting updated
I am trying to create a list of employee. I can assign username, password and email to that employee and also can update employee information where I should able to update username, password or email either. I could create an employee and also create the username and password along with update employee info but when changing the username or password or email of the employee a new user is created.

Here is what I have tried

```<code>class EmployeeForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = models.Employee
        fields = ('name', 'designation', 'section', 'phone_number', 'mobile_number',
                  'email', 'gender', 'role', 'username', 'password', 'avatar',)

def employee(request):
    form = EmployeeForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        office_instance = OfficeSetup.objects.get(owner=request.user)
        form = form.save(commit=False)
        form.office = office_instance
        user = User.objects.create_user(
            username=username, password=password, email=email)
        user.save()
        form.save()
        messages.success(request, 'Thank you')
        return redirect('employee-list')
    messages.warning(request, 'Error')
    context = {
        'form': form
    }
    return render(request, 'dashboard/hrm/employee.html', context)
</code>```

Edit part

```<code>def edit_employee(request, id):
    instance = get_object_or_404(Employee, id=id)
    form = EmployeeForm(request.POST or None, instance=instance)
    if request.method == "POST" and form.is_valid():
        employee = Employee.objects.get(id=id)
        prev_username = employee.username
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        office_instance = OfficeSetup.objects.get(owner=request.user)
        form = form.save(commit=False)
        form.office = office_instance
        # change username or password or email if admin has done the changes in
        # those field
        try:
            user_instance = User.objects.get(username=prev_username)
            user_instance.username = username
            user_instance.set_password(password)
            user_instance.email = email
            form.save()
            user_instance.save()
        except User.DoesNotExist:
            messages.error(request, "Following User Does Not Exist!")
        except:
            user = User.objects.create_user(
                username=username, password=password, email=email)
            form.save()
            user.save()
            messages.success(request, "Thank you")
            return redirect('employee-list')
    messages.warning(request, "Error")
    context = {
        'form': form
    }
    return render(request, 'dashboard/hrm/employee.html', context)
</code>```

Screenshot is to make the flow or use-case clear

UPDATED CODE

```<code>def edit_employee(request, id):
    instance = get_object_or_404(Employee, id=id)
    form = EmployeeForm(request.POST or None, instance=instance)
    if request.method == "POST" and form.is_valid():
        employee = Employee.objects.get(id=id)
        prev_username = employee.username
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        office_instance = OfficeSetup.objects.get(owner=request.user)
        form = form.save(commit=False)
        form.office = office_instance
        # change username or password or email if admin has done the changes in
        # those field
        user, created = User.objects.get_or_create(username=prev_username)
        if created:
            user.set_password(password)
            user.email = email
            form.save()
            user.save()
            return redirect('employee-list')
        user.set_password(password)
        user.email = email
        form.save()
        user.save()
        return redirect('employee-list')
    messages.warning(request, "Error")
    context = {
        'form': form
    }
    return render(request, 'dashboard/hrm/employee.html', context)
</code>```

答:
The get_or_create method is made for cases like this. I'd refactor to do something like this:

```<code>user, created = User.objects.get_or_create(username=username)

if created:
    # Fields to only populated on creation
    user.password = password
    ...etc...

# Fields to update on creation or update
user.email = email
...etc...
user.save()
</code>```

Details here: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#get-or-create

Good luck!

Body:
I am trying to create a list of employee. I can assign username, password and email to that employee and also can update employee information where I should able to update username, password or email either. I could create an employee and also create the username and password along with update employee info but when changing the username or password or email of the employee a new user is created.

Here is what I have tried

class EmployeeForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = models.Employee
        fields = ('name', 'designation', 'section', 'phone_number', 'mobile_number',
                  'email', 'gender', 'role', 'username', 'password', 'avatar',)

def employee(request):
    form = EmployeeForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        office_instance = OfficeSetup.objects.get(owner=request.user)
        form = form.save(commit=False)
        form.office = office_instance
        user = User.objects.create_user(
            username=username, password=password, email=email)
        user.save()
        form.save()
        messages.success(request, 'Thank you')
        return redirect('employee-list')
    messages.warning(request, 'Error')
    context = {
        'form': form
    }
    return render(request, 'dashboard/hrm/employee.html', context)

Edit part

def edit_employee(request, id):
    instance = get_object_or_404(Employee, id=id)
    form = EmployeeForm(request.POST or None, instance=instance)
    if request.method == "POST" and form.is_valid():
        employee = Employee.objects.get(id=id)
        prev_username = employee.username
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        office_instance = OfficeSetup.objects.get(owner=request.user)
        form = form.save(commit=False)
        form.office = office_instance
        # change username or password or email if admin has done the changes in
        # those field
        try:
            user_instance = User.objects.get(username=prev_username)
            user_instance.username = username
            user_instance.set_password(password)
            user_instance.email = email
            form.save()
            user_instance.save()
        except User.DoesNotExist:
            messages.error(request, "Following User Does Not Exist!")
        except:
            user = User.objects.create_user(
                username=username, password=password, email=email)
            form.save()
            user.save()
            messages.success(request, "Thank you")
            return redirect('employee-list')
    messages.warning(request, "Error")
    context = {
        'form': form
    }
    return render(request, 'dashboard/hrm/employee.html', context)

Screenshot is to make the flow or use-case clear

UPDATED CODE

def edit_employee(request, id):
    instance = get_object_or_404(Employee, id=id)
    form = EmployeeForm(request.POST or None, instance=instance)
    if request.method == "POST" and form.is_valid():
        employee = Employee.objects.get(id=id)
        prev_username = employee.username
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']
        office_instance = OfficeSetup.objects.get(owner=request.user)
        form = form.save(commit=False)
        form.office = office_instance
        # change username or password or email if admin has done the changes in
        # those field
        user, created = User.objects.get_or_create(username=prev_username)
        if created:
            user.set_password(password)
            user.email = email
            form.save()
            user.save()
            return redirect('employee-list')
        user.set_password(password)
        user.email = email
        form.save()
        user.save()
        return redirect('employee-list')
    messages.warning(request, "Error")
    context = {
        'form': form
    }
    return render(request, 'dashboard/hrm/employee.html', context)

Body:
The get_or_create method is made for cases like this. I'd refactor to do something like this:

user, created = User.objects.get_or_create(username=username)

if created:
    # Fields to only populated on creation
    user.password = password
    ...etc...

# Fields to update on creation or update
user.email = email
...etc...
user.save()

Details here: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#get-or-create

Good luck!


来源: stackexchange

问:
EntityDataSource replace * with % wildcard on queries
I have an application that uses EntityDataSource in many places.

In the EDS, I manually build the Where clause based on user input from TextBox'es.

I would like the user to be able to enter "*" (asterisks) instead of "%" when querying data.

Is there an easy as using Entity SQL or the EDS itself to do a search/replace? I know I could actually change the TextBox after the data is entered, but when the user sees his text was changed from an * to a % I don't think he will understand.

I have tried using the T-SQL Replace command and doing something like this:

```<code><asp:EntityDataSource ID="EDSParts" runat="server"
    ConnectionString="name=TTEntities" DefaultContainerName="TTEntities"
    EnableFlattening="False" EntitySetName="Parts"
    OrderBy="it.ID DESC"
    Where ="(CASE
                WHEN (@PartNumber IS NOT NULL) THEN
                    it.[Number] LIKE REPLACE(@PartNumber, "*", "%")
                ELSE
                    it.[ID] IS NOT NULL
            END)">
    <WhereParameters>
        <asp:ControlParameter Name="PartNumber" Type="String"
            ControlID="txtPartNumberQuery" PropertyName="Text" />
    </WhereParameters>
</asp:EntityDataSource>
</code>```

But I get a "Server tag is not well formed" message. I can't find an equivalent "replace" function in the Entity SQL reference....

Any ideas?

答:
Sluama - Your suggestion fixed it! Such an obvious answer. The " was terminating the Where clause string. I could have sworn I tried that, but I guess not. Becuase, I just happened to come back to this question and saw your answer and it works!</p>

```<code><asp:EntityDataSource ID="EDSParts" runat="server"
    ConnectionString="name=TTEntities" DefaultContainerName="TTEntities"
    EnableFlattening="False" EntitySetName="Parts"
    OrderBy="it.ID DESC"
    Where ="(CASE
                WHEN (@PartNumber IS NOT NULL) THEN
                    it.[Number] LIKE REPLACE(@PartNumber, '*', '%')
                ELSE
                    it.[ID] IS NOT NULL
             END)">
    <WhereParameters>
        <asp:ControlParameter Name="PartNumber" Type="String"
            ControlID="txtPartNumberQuery" PropertyName="Text" />
    </WhereParameters>
</asp:EntityDataSource>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an application that uses EntityDataSource in many places.

In the EDS, I manually build the Where clause based on user input from TextBox'es.

I would like the user to be able to enter "*" (asterisks) instead of "%" when querying data.

Is there an easy as using Entity SQL or the EDS itself to do a search/replace? I know I could actually change the TextBox after the data is entered, but when the user sees his text was changed from an * to a % I don't think he will understand.

I have tried using the T-SQL Replace command and doing something like this:

<asp:EntityDataSource ID="EDSParts" runat="server"
    ConnectionString="name=TTEntities" DefaultContainerName="TTEntities"
    EnableFlattening="False" EntitySetName="Parts"
    OrderBy="it.ID DESC"
    Where ="(CASE
                WHEN (@PartNumber IS NOT NULL) THEN
                    it.[Number] LIKE REPLACE(@PartNumber, "*", "%")
                ELSE
                    it.[ID] IS NOT NULL
            END)">
    <WhereParameters>
        <asp:ControlParameter Name="PartNumber" Type="String"
            ControlID="txtPartNumberQuery" PropertyName="Text" />
    </WhereParameters>
</asp:EntityDataSource>

But I get a "Server tag is not well formed" message. I can't find an equivalent "replace" function in the Entity SQL reference....

Any ideas?

Body:
Sluama - Your suggestion fixed it! Such an obvious answer. The " was terminating the Where clause string. I could have sworn I tried that, but I guess not. Becuase, I just happened to come back to this question and saw your answer and it works!

<asp:EntityDataSource ID="EDSParts" runat="server"
    ConnectionString="name=TTEntities" DefaultContainerName="TTEntities"
    EnableFlattening="False" EntitySetName="Parts"
    OrderBy="it.ID DESC"
    Where ="(CASE
                WHEN (@PartNumber IS NOT NULL) THEN
                    it.[Number] LIKE REPLACE(@PartNumber, '*', '%')
                ELSE
                    it.[ID] IS NOT NULL
             END)">
    <WhereParameters>
        <asp:ControlParameter Name="PartNumber" Type="String"
            ControlID="txtPartNumberQuery" PropertyName="Text" />
    </WhereParameters>
</asp:EntityDataSource>


问:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'map' of undefined
The below error happens only when it tries to return value from the catch. Hope I'm doing a fundamentally wrong thing here.Please give me a clue.Why can't I return an observable from catch?

.ts

```<code>  getMyTopic() {
    return this.topicSer.getMyTopics().map((res: any) => res.json()).map((res: any) => res = res.categories)
      .catch((err: any) => {
        console.log('err', err);
        return []
      })
  }
</code>```

provider.ts

```<code>  getMyTopics(): Observable<any> {
       if (typeof this.userService.userDetails != 'undefined') {
          this.localCacheService.getItem(this.localCacheService.discoverTopicsKey).then((val) => {
        if (val != null && val.length == 0) return this.apiService.get(config.discover_topic_WITHAUTH);
         }).catch(() => {
       return this.apiService.get(config.discover_topic_WITHOUTAUTH);//here is the issue
          });
        }
</code>```

Error

```<code>ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
    at Discover.webpackJsonp.402.Discover.getMyTopic (discover.ts:123)
    at Discover.webpackJsonp.402.Discover.getData (discover.ts:69)
    at discover.ts:51
    at t.invoke (polyfills.js:3)
    at Object.onInvoke (core.js:4626)
    at t.invoke (polyfills.js:3)
    at r.run (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4617)
    at Discover.webpackJsonp.402.Discover.getMyTopic (discover.ts:123)
    at Discover.webpackJsonp.402.Discover.getData (discover.ts:69)
    at discover.ts:51
    at t.invoke (polyfills.js:3)
    at Object.onInvoke (core.js:4626)
    at t.invoke (polyfills.js:3)
    at r.run (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4617)
    at c (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4617)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)
    at o (polyfills.js:3)
    at e.invokeTask [as invoke] (polyfills.js:3)
    at p (polyfills.js:2)
    at IDBRequest.v (polyfills.js:2)
defaultErrorLogger @ core.js:1350
ErrorHandler.handleError @ core.js:1411
IonicErrorHandler.handleError @ ionic-error-handler.js:61
next @ core.js:5373
schedulerFn @ core.js:4220
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.js:4200
(anonymous) @ core.js:4648
t.invoke @ polyfills.js:3
r.run @ polyfills.js:3
NgZone.runOutsideAngular @ core.js:4574
onHandleError @ core.js:4648
t.handleError @ polyfills.js:3
r.runGuarded @ polyfills.js:3
(anonymous) @ polyfills.js:3
n.microtaskDrainDone @ polyfills.js:3
o @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2
IndexedDB (async)
(anonymous) @ localforage.js:826
t.invoke @ polyfills.js:3
onInvoke @ core.js:4626
t.invoke @ polyfills.js:3
r.run @ polyfills.js:3
(anonymous) @ polyfills.js:3
t.invokeTask @ polyfills.js:3
onInvokeTask @ core.js:4617
t.invokeTask @ polyfills.js:3
r.runTask @ polyfills.js:3
o @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2
</code>```

答: The getMyTopics method doesn't return anything. Also the catch operator is returning an empty array when it should return an Observable.

ContentLicense: CC BY-SA 3.0

Body:
The below error happens only when it tries to return value from the catch. Hope I'm doing a fundamentally wrong thing here.Please give me a clue.Why can't I return an observable from catch?

.ts

  getMyTopic() {
    return this.topicSer.getMyTopics().map((res: any) => res.json()).map((res: any) => res = res.categories)
      .catch((err: any) => {
        console.log('err', err);
        return []
      })
  }

provider.ts

  getMyTopics(): Observable<any> {
       if (typeof this.userService.userDetails != 'undefined') {
          this.localCacheService.getItem(this.localCacheService.discoverTopicsKey).then((val) => {
        if (val != null && val.length == 0) return this.apiService.get(config.discover_topic_WITHAUTH);
         }).catch(() => {
       return this.apiService.get(config.discover_topic_WITHOUTAUTH);//here is the issue
          });
        }

Error

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
    at Discover.webpackJsonp.402.Discover.getMyTopic (discover.ts:123)
    at Discover.webpackJsonp.402.Discover.getData (discover.ts:69)
    at discover.ts:51
    at t.invoke (polyfills.js:3)
    at Object.onInvoke (core.js:4626)
    at t.invoke (polyfills.js:3)
    at r.run (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4617)
    at Discover.webpackJsonp.402.Discover.getMyTopic (discover.ts:123)
    at Discover.webpackJsonp.402.Discover.getData (discover.ts:69)
    at discover.ts:51
    at t.invoke (polyfills.js:3)
    at Object.onInvoke (core.js:4626)
    at t.invoke (polyfills.js:3)
    at r.run (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4617)
    at c (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4617)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)
    at o (polyfills.js:3)
    at e.invokeTask [as invoke] (polyfills.js:3)
    at p (polyfills.js:2)
    at IDBRequest.v (polyfills.js:2)
defaultErrorLogger @ core.js:1350
ErrorHandler.handleError @ core.js:1411
IonicErrorHandler.handleError @ ionic-error-handler.js:61
next @ core.js:5373
schedulerFn @ core.js:4220
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.js:4200
(anonymous) @ core.js:4648
t.invoke @ polyfills.js:3
r.run @ polyfills.js:3
NgZone.runOutsideAngular @ core.js:4574
onHandleError @ core.js:4648
t.handleError @ polyfills.js:3
r.runGuarded @ polyfills.js:3
(anonymous) @ polyfills.js:3
n.microtaskDrainDone @ polyfills.js:3
o @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2
IndexedDB (async)
(anonymous) @ localforage.js:826
t.invoke @ polyfills.js:3
onInvoke @ core.js:4626
t.invoke @ polyfills.js:3
r.run @ polyfills.js:3
(anonymous) @ polyfills.js:3
t.invokeTask @ polyfills.js:3
onInvokeTask @ core.js:4617
t.invokeTask @ polyfills.js:3
r.runTask @ polyfills.js:3
o @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2


问:
connect Google App Engine and Google Compute Engine
I created a VM instance in Googl Compute Engine and app in Google App Engine standard environment. I was planning to have my app in App Engine and my database server in Compute Engine. But, I can't connect between the both by internal IP. Is this possible? the app and db are in the same zone (us-east1) but the connection by IP don't work, only work with external IP. Apparently, the rules of firewall are correct.

答: You will have to connect using the external IP address of the service running on your Compute Engine instance. App Engine standard environment is on a different network than the Compute Engine instances and don't have private IP access to each other currently. Switching to an application (or service of an application) on the flexible environment might work for you if the costs associated make sense.</p>


问:
Validate or remove for extra fields in laravel
It's posible to validate request with rules for additional fields, or remove that fields from request?

Simple example, I have FormRequest object with rules:

public function rules() {
        return [
            'id' => 'required|integer',
            'company_name' => 'required|max:255',
        ];
    }
```

And when I get post request with any other fields I want to get error/exception in controller or I want to get only id and company_name fields, with no any others. It's exist any feature in laravel with that, or I must make it in my way?

答:
Starting form Laravel 5.5 you can call validate method right on Request e.g.

```<code>class YourController extends Controller
{

    public function store(Request $request) {

      $cleanData = $request->validate([
        'id' => 'required|integer',
        'company_name' => 'required|max:255',
      ]);

      // Now you may safely pass $cleanData right to your model
      // because it ONLY contains fields that in your rules e.g

      $yourModel->create($cleanData);
  }
}
</code>```

Body:
It's posible to validate request with rules for additional fields, or remove that fields from request?

Simple example, I have FormRequest object with rules:

public function rules() {
        return [
            'id' => 'required|integer',
            'company_name' => 'required|max:255',
        ];
    }

And when I get post request with any other fields I want to get error/exception in controller or I want to get only id and company_name fields, with no any others. It's exist any feature in laravel with that, or I must make it in my way?

Body:
Starting form Laravel 5.5 you can call validate method right on Request e.g.

class YourController extends Controller
{

    public function store(Request $request) {

      $cleanData = $request->validate([
        'id' => 'required|integer',
        'company_name' => 'required|max:255',
      ]);

      // Now you may safely pass $cleanData right to your model
      // because it ONLY contains fields that in your rules e.g

      $yourModel->create($cleanData);
  }
}


问:
Selecting multiple tables for a Query MySQLi PHP
I am trying to create a query, but I don't know how to select multiple tables with the way I have my database set up.

In my query I am trying to display what movies have what actor, but each movie has multiple actors so I have to select from three tables.
This is my movies table:

This is my actor_information table

My last table is the actor_movie table. This table correlates the movie_id with and actor_id

I have the following php to connect to the database, but I am not sure how to write the query portion.

```<code><?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';

$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully <br>";

// this code is wrong, but i get the general idea of how to select from my db.
$sql = "SELECT actor_movie, movies, actor_information FROM actor_movie INNER
JOIN movies ON actor_movie.movie_id = movies.movie_id
INNER JOIN actor_information ON actor_movie.actor_id =
actor_information.actor_id"
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo " Title " . $row["title"]. "". $row["actor_id"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>
</code>```

Here is my uml if it helps:

答:
Use this
=>

select movie.movie_name AS Movie, GROUP_CONCAT(actor_name.actor_name)
  AS Actor FROM movie INNER JOIN relation_table ON movie.id =
  relation_table.movie_id INNER JOIN actor_name ON actor_name.id =
  relation_table.actor_id GROUP BY movie.id

Body:
I am trying to create a query, but I don't know how to select multiple tables with the way I have my database set up.

In my query I am trying to display what movies have what actor, but each movie has multiple actors so I have to select from three tables.
This is my movies table:

This is my actor_information table

My last table is the actor_movie table. This table correlates the movie_id with and actor_id

I have the following php to connect to the database, but I am not sure how to write the query portion.

<?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';

$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully
";

// this code is wrong, but i get the general idea of how to select from my db.
$sql = "SELECT actor_movie, movies, actor_information FROM actor_movie INNER
JOIN movies ON actor_movie.movie_id = movies.movie_id
INNER JOIN actor_information ON actor_movie.actor_id =
actor_information.actor_id"
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo " Title " . $row["title"]. "". $row["actor_id"]. "
";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>

Here is my uml if it helps:


问:
How to read an image and text value in C#?

As you can see, I am trying to send an image, and a name through a POST command to a local function.

How Can I read both of these parameters in C#?

This is what I have tried but It can only read File Image.

```<code>   [FunctionName("Test")]
public static async Task<HttpResponseMessage>
     Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route =
 null)]HttpRequestMessage req, TraceWriter log)
{
    //Check if the request contains multipart/form-data.
    if (!req.Content.IsMimeMultipartContent())
    {
        return req.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }

  foreach (var stream in contents.Contents)
    {

        try
        {
            var fileBytes = await stream.ReadAsByteArrayAsync();
            var fileinfo = new FileInfo(stream.Headers.ContentDisposition.FileName.Trim('"'));

         //Can Read File image like this.

        }
        catch(Exception e)
        {
            return req.CreateErrorResponse(HttpStatusCode.Conflict, e);
        }
</code>```

答:
You can use MultipartFormDataStreamProvider

Use FileData property to get the posted files

Use FormData property to get the values of any form data posted based upon the key.

Check this File Upload and Multipart MIME.

Body:
As you can see, I am trying to send an image, and a name through a POST command to a local function.

How Can I read both of these parameters in C#?

This is what I have tried but It can only read File Image.

   [FunctionName("Test")]
public static async Task<HttpResponseMessage>
     Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route =
 null)]HttpRequestMessage req, TraceWriter log)
{
    //Check if the request contains multipart/form-data.
    if (!req.Content.IsMimeMultipartContent())
    {
        return req.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }

  foreach (var stream in contents.Contents)
    {

        try
        {
            var fileBytes = await stream.ReadAsByteArrayAsync();
            var fileinfo = new FileInfo(stream.Headers.ContentDisposition.FileName.Trim('"'));

         //Can Read File image like this.

        }
        catch(Exception e)
        {
            return req.CreateErrorResponse(HttpStatusCode.Conflict, e);
        }


问:
extract value from field in javascript
I'm trying to get the output to be what the user types in to the input field but it says "undefined" when I press submit. Why is this and how do I fix it, Thanks

function myFunction() {
  document.getElementById("output").innerHTML = document.getElementById("input").value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="input" action="/action_page.php">
  input: <input type="text" name="input"><br><br>
  <input type="button" onclick="myFunction()" value="Submit">
</form>

<p id="output"></p></code>```

I got it, i had 2 things with the same id

答:
you are trying to get the value of element whose id is input as per the javascript code:

```<code>document.getElementById("input").value
</code>```

Now the form has this id, so it is giving you undefined.
Assign another id to your input type="text" and use it in document.getElementById("input").value , your code will work fine

Title: extract value from field in javascript

Body:
I'm trying to get the output to be what the user types in to the input field but it says "undefined" when I press submit. Why is this and how do I fix it, Thanks

function myFunction() {
  document.getElementById("output").innerHTML = document.getElementById("input").value;
}

<form id="input" action="/action_page.php">
  input: <input type="text" name="input">

  <input type="button" onclick="myFunction()" value="Submit">
</form>

I got it, i had 2 things with the same id

Body:
you are trying to get the value of element whose id is input as per the javascript code:

document.getElementById("input").value

Now the form has this id, so it is giving you undefined.
Assign another id to your input type="text" and use it in document.getElementById("input").value , your code will work fine


问:
Create one-way relationship without foreign key
I've got a problem with relationships I'm trying to form between some models.

I have a Node which has many NodeTasks. This is modelled so that NodeTask belongs_to :node, which works as expected.

I would also like to add a reference to an arbitrary NodeTask on Node - let's say first_node_task, as an optional attribute. This is where I'm having trouble.

I was able to hack it together so that node.first_node_task could be set and worked as expected with the following migration:

```<code>add_reference :nodes, :first_node_task, { type: :uuid, foreign_key: { to_table: :node_tasks } }
</code>```

And model:

```<code>class Node
  belongs_to :first_node_task, class_name: 'NodeTask', foreign_key: 'first_node_task_id', optional: true
end
</code>```

However, I found that I could no longer delete those Nodes, because of the reference to NodeTask. There was some weird reverse relationship going on with the foreign key constraint: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table "nodes" violates foreign key constraint "fk_rails_696709283b" on table "node_tasks"

How can I model my references so that Node can have a first_node_task set, which is a reference to an arbitrary NodeTask, without affecting the related NodeTask?

答:
It turns out what I'm trying to do doesn't make sense.

Irrelevant to my first_node_task attribute, Nodes have a set of NodeTasks, so something needs to happen to those NodeTasks on Node deletion. Whatever happens to child NodeTasks will happen to the first_node_task, because it is one of them.

I realised that I do actually want NodeTasks to be deleted, which mean that if first_node_task is set, it would be deleted also.

I solved this by adding a migration to change the foreign key between NodeTask and Node to cascade on deletion, as so:

```<code>remove_foreign_key :node_tasks, :nodes
add_foreign_key :node_tasks, :nodes, on_delete: :cascade
</code>```

Body:
I've got a problem with relationships I'm trying to form between some models.

I have a Node which has many NodeTasks. This is modelled so that NodeTask belongs_to :node, which works as expected.

I would also like to add a reference to an arbitrary NodeTask on Node - let's say first_node_task, as an optional attribute. This is where I'm having trouble.

I was able to hack it together so that node.first_node_task could be set and worked as expected with the following migration:

add_reference :nodes, :first_node_task, { type: :uuid, foreign_key: { to_table: :node_tasks } }

And model:

class Node
  belongs_to :first_node_task, class_name: 'NodeTask', foreign_key: 'first_node_task_id', optional: true
end

However, I found that I could no longer delete those Nodes, because of the reference to NodeTask. There was some weird reverse relationship going on with the foreign key constraint: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  update or delete on table "nodes" violates foreign key constraint "fk_rails_696709283b" on table "node_tasks"

How can I model my references so that Node can have a first_node_task set, which is a reference to an arbitrary NodeTask, without affecting the related NodeTask?

Body:
It turns out what I'm trying to do doesn't make sense.

Irrelevant to my first_node_task attribute, Nodes have a set of NodeTasks, so something needs to happen to those NodeTasks on Node deletion. Whatever happens to child NodeTasks will happen to the first_node_task, because it is one of them.

I realised that I do actually want NodeTasks to be deleted, which mean that if first_node_task is set, it would be deleted also.

I solved this by adding a migration to change the foreign key between NodeTask and Node to cascade on deletion, as so:

remove_foreign_key :node_tasks, :nodes
add_foreign_key :node_tasks, :nodes, on_delete: :cascade


问:
Change column name in a table in Clickhouse
Is there any way to ALTER a table and change the column name in clickhouse?
I only found to change tha table name but not for an individual column in a straight forward way.

Thanks.

答:
You can try use CREATE TABLE new_table with another field name
and run INSERT INTO new_table SELECT old_field AS new_field FROM old_table</p>


问:
mainframe - generate a report with sum of particular fields
I have a VSAM which has

• 4-byte binary unsigned integer representing a 6-digit decimal branch sortcode (e.g. 420101)

• 4-byte binary unsigned integer representing an 8-digit account number (e.g. 12345678)

• 4-byte signed integer holding the account's current balance

• 32-byte EBCDIC character account owner name (e.g. “PAT JONES”), blank padded on the right

and I want to generate a report as below

I was trying to do this

```<code>  INCLUDE COND=(1,7,CH,EQ,C'some sortcode')
  SORT FIELDS=(1,7,CH,A)
  SUM FIELDS=(9,2,BI)
</code>```

But there's plenty of sortcode. I am thinking of sort all the inputs and then sum every record that has the same sortcode together right underneath these sortcode rows. Is there any way in JCL I can do that? Thanks.

答:
Try this:

```<code>//SORTSTEP EXEC PGM=SORT
//SYSOUT   DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTIN   DD DSN=YourInputDataset,DISP=SHR
//SORTOUT  DD DSN=YourOutputDataset,
//          DISP=(NEW,CATLG,DELETE)
//SYSIN  DD *
  SORT FIELDS=(1,4,BI,A)
  INREC BUILD=(1,4,BI,TO=ZD,LENGTH=6,5,4,9,4,13,32)
  OUTFIL REMOVECC,
         SECTIONS=(1,6,
         HEADER3=(1:C'LIST OF BANK BY BRANCH',/,X,/,
                  1:C'SORTCODE:    ',1,6,/,X,/,
                  1:C'ACCOUNT',10:C'BALANCE',20:C'OWNER NAME',/,
                  1:C'-------',10:C'-------',20:C'----------'),
         TRAILER3=(X,/,
      1:C'BRANCH TOTAL: ',16:TOT=(11,4,BI,EDIT=(SIIIITTT),SIGNS=(,-)))),
         TRAILER1=(X,/,1:C'GRAND TOTAL: ',TOT=(11,4,BI,
                        EDIT=(SIIIITTT),SIGNS=(,-))),
        OUTREC=(1:7,4,BI,TO=ZD,LENGTH=8,10:11,4,BI,EDIT=(SIIIITTT),
                        SIGNS=(,-),20:15,32)
/*
</code>```

You can find about more about SECTIONS, HEADER3 and TRAILER3 at this link: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.iceg200/ice2cg_Sections.htm

Body:
I have a VSAM which has

• 4-byte binary unsigned integer representing a 6-digit decimal branch sortcode (e.g. 420101)

• 4-byte binary unsigned integer representing an 8-digit account number (e.g. 12345678)

• 4-byte signed integer holding the account's current balance

• 32-byte EBCDIC character account owner name (e.g. “PAT JONES”), blank padded on the right

and I want to generate a report as below

I was trying to do this

  INCLUDE COND=(1,7,CH,EQ,C'some sortcode')
  SORT FIELDS=(1,7,CH,A)
  SUM FIELDS=(9,2,BI)

But there's plenty of sortcode. I am thinking of sort all the inputs and then sum every record that has the same sortcode together right underneath these sortcode rows. Is there any way in JCL I can do that? Thanks.

Body:
Try this:

//SORTSTEP EXEC PGM=SORT
//SYSOUT   DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTIN   DD DSN=YourInputDataset,DISP=SHR
//SORTOUT  DD DSN=YourOutputDataset,
//          DISP=(NEW,CATLG,DELETE)
//SYSIN  DD *
  SORT FIELDS=(1,4,BI,A)
  INREC BUILD=(1,4,BI,TO=ZD,LENGTH=6,5,4,9,4,13,32)
  OUTFIL REMOVECC,
         SECTIONS=(1,6,
         HEADER3=(1:C'LIST OF BANK BY BRANCH',/,X,/,
                  1:C'SORTCODE:    ',1,6,/,X,/,
                  1:C'ACCOUNT',10:C'BALANCE',20:C'OWNER NAME',/,
                  1:C'-------',10:C'-------',20:C'----------'),
         TRAILER3=(X,/,
      1:C'BRANCH TOTAL: ',16:TOT=(11,4,BI,EDIT=(SIIIITTT),SIGNS=(,-)))),
         TRAILER1=(X,/,1:C'GRAND TOTAL: ',TOT=(11,4,BI,
                        EDIT=(SIIIITTT),SIGNS=(,-))),
        OUTREC=(1:7,4,BI,TO=ZD,LENGTH=8,10:11,4,BI,EDIT=(SIIIITTT),
                        SIGNS=(,-),20:15,32)
/*

You can find about more about SECTIONS, HEADER3 and TRAILER3 at this link: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.iceg200/ice2cg_Sections.htm


答:
You need to add an id to your input field and not the form. Or you need to create a new id for the input field.

function myFunction() {
  document.getElementById("output").innerHTML = document.getElementById("input").value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="/action_page.php">
  input: <input type="text" name="input" id="input"><br><br>
  <input type="button" onclick="myFunction()" value="Submit">
</form>

<p id="output"></p></code>```

You could also use selectors #input > [type=text] like this:

function myFunction() {
  document.getElementById("output").innerHTML = document.querySelector("#input > [type=text]").value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="input" action="/action_page.php">
  input: <input type="text" name="input"><br><br>
  <input type="button" onclick="myFunction()" value="Submit">
</form>

<p id="output"></p></code>```

Title: extract value from field in javascript

Body:
You need to add an id to your input field and not the form. Or you need to create a new id for the input field.

function myFunction() {
  document.getElementById("output").innerHTML = document.getElementById("input").value;
}

<form action="/action_page.php">
  input: <input type="text" name="input" id="input"><br><br>
  <input type="button" onclick="myFunction()" value="Submit">
</form>

<p id="output"></p>

You could also use selectors #input > [type=text] like this:

function myFunction() {
  document.getElementById("output").innerHTML = document.querySelector("#input > [type=text]").value;
}

<form id="input" action="/action_page.php">
  input: <input type="text" name="input"><br><br>
  <input type="button" onclick="myFunction()" value="Submit">
</form>

<p id="output"></p>


问:
Unable to connect to mongo server
Im using mongoDb V 3.4 and trying to start the server but it says

```<code>C:\Users\gokul ram>mongo
MongoDB shell version v3.4.10
connecting to: mongodb://127.0.0.1:27017
2017-11-18T09:25:27.061+0530 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017 after 5000ms milliseconds, giving up.
2017-11-18T09:25:27.062+0530 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:237:13
@(connect):1:6
exception: connect failed
</code>```

I also tried with --dbpath command, but it is waiting for connection for long time, still not getting connected

```<code>C:\Program Files\MongoDB\Server\3.4\bin>mongod --dbpath "C:/data/db"
2017-11-18T09:36:03.368+0530 I CONTROL  [initandlisten] MongoDB starting :     pid=4660 port=27017 dbpath=C:/data/db 64-bit host=GOK_RAM
2017-11-18T09:36:03.370+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2017-11-18T09:36:03.370+0530 I CONTROL  [initandlisten] db version v3.4.10
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] git version: 078f28920cb24de0dd479b5ea6c66c644f6326e9
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1u-fips  22 Sep 2016
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] modules: none
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] build environment:
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten]     distarch: x86_64
2017-11-18T09:36:03.372+0530 I CONTROL  [initandlisten]     target_arch: x86_64
2017-11-18T09:36:03.372+0530 I CONTROL  [initandlisten] options: { storage: { dbPath: "C:/data/db" } }
2017-11-18T09:36:03.375+0530 I -        [initandlisten] Detected data files in C:/data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2017-11-18T09:36:03.376+0530 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=1509M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2017-11-18T09:36:04.096+0530 I CONTROL  [initandlisten]
2017-11-18T09:36:04.097+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-11-18T09:36:04.097+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-11-18T09:36:04.098+0530 I CONTROL  [initandlisten]
2017-11-18T09:36:04.098+0530 I CONTROL  [initandlisten] Hotfix KB2731284 or later update is not installed, will zero-out data files.
2017-11-18T09:36:04.098+0530 I CONTROL  [initandlisten]
2017-11-18T09:36:05.880+0530 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/data/db/diagnostic.data'
2017-11-18T09:36:05.882+0530 I NETWORK  [thread1] waiting for connections on port 27017
</code>```

Is that problem with the mongo db version or my configurations? Any faced the same issue please help me!! Thanks in advance

答:
First: navigate to C:\Program Files\MongoDB\Server\3.4\bin\ and run mongod.exe this will start the server .

second : in a new cmd typein mongo
 this might work

Title: Unable to connect to mongo server

Body:
Im using mongoDb V 3.4 and trying to start the server but it says

C:\Users\gokul ram>mongo
MongoDB shell version v3.4.10
connecting to: mongodb://127.0.0.1:27017
2017-11-18T09:25:27.061+0530 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017 after 5000ms milliseconds, giving up.
2017-11-18T09:25:27.062+0530 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:237:13
@(connect):1:6
exception: connect failed

I also tried with --dbpath command, but it is waiting for connection for long time, still not getting connected

C:\Program Files\MongoDB\Server\3.4\bin>mongod --dbpath "C:/data/db"
2017-11-18T09:36:03.368+0530 I CONTROL  [initandlisten] MongoDB starting :     pid=4660 port=27017 dbpath=C:/data/db 64-bit host=GOK_RAM
2017-11-18T09:36:03.370+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2017-11-18T09:36:03.370+0530 I CONTROL  [initandlisten] db version v3.4.10
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] git version: 078f28920cb24de0dd479b5ea6c66c644f6326e9
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1u-fips  22 Sep 2016
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] modules: none
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten] build environment:
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
2017-11-18T09:36:03.371+0530 I CONTROL  [initandlisten]     distarch: x86_64
2017-11-18T09:36:03.372+0530 I CONTROL  [initandlisten]     target_arch: x86_64
2017-11-18T09:36:03.372+0530 I CONTROL  [initandlisten] options: { storage: { dbPath: "C:/data/db" } }
2017-11-18T09:36:03.375+0530 I -        [initandlisten] Detected data files in C:/data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2017-11-18T09:36:03.376+0530 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=1509M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2017-11-18T09:36:04.096+0530 I CONTROL  [initandlisten]
2017-11-18T09:36:04.097+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-11-18T09:36:04.097+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-11-18T09:36:04.098+0530 I CONTROL  [initandlisten]
2017-11-18T09:36:04.098+0530 I CONTROL  [initandlisten] Hotfix KB2731284 or later update is not installed, will zero-out data files.
2017-11-18T09:36:04.098+0530 I CONTROL  [initandlisten]
2017-11-18T09:36:05.880+0530 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/data/db/diagnostic.data'
2017-11-18T09:36:05.882+0530 I NETWORK  [thread1] waiting for connections on port 27017

Is that problem with the mongo db version or my configurations? Any faced the same issue please help me!! Thanks in advance


问:
Vista 64-bit Development Caveats
I'm migrating my development workstation from 32-bit Vista to 64-bit Vista.

The production platform is 32-bit Windows Server and SQL Server 2008.

Does anyone know of any issues with migrating the code base?

EDIT:

the system consists of web forms, c# code, stored procedures.

there is also ajax.net, ssrs, ssis, and dynamic reports/graphs from dundas.

however, i think other users might appreciate any lessons learned or feedback in general regarding this move.

FINDINGS:

As of Jan 24, 2009

Checkpoint VPN does not support Vista 64 (actually it seems that very few do)

Cropper utility required special download and rebuild to work on Vista 64 (Cropper looks very nice, but it lacks scrollable window capture)

The lack of support for Vista 64 made it not worth while for me.  I wish someone would have mentioned the lack of VPN support, but there is currently no vpn vendor that supports 64 bit clients....  So be forwarned - as of 1/28/2009 - using Vista 64 is not a good option for those of us who need vpn.

答: I had much trouble with adding 3rd party 32 bit ISAPI handler to IIS on 64 bit w2k3 server (php) I had to make IIS run in 32 bit compatibility mode. If it's all managed I can think of no serious problem though.</p>

OwnerDisplayName: mson

Title: Vista 64-bit Development Caveats

LastEditorDisplayName: mson

OwnerDisplayName: Spikolynn


问:
What does '@' char mean before parameter name in method declaration?

Possible Duplicates:

  What does the @ symbol before a variable name mean in C#?

  What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

```<code>protected void Method1(Type1 @arg1, Type2 arg2)
...
</code>```

I use c# with .net 3.5.

Thanks.

答: It allows reserved words to be used as identifiers. It is usually used by code generators which may be using source names from systems with different keywords than the target language e.g. table names and sproc argument names.</p>

Body:
Possible Duplicates:

  What does the @ symbol before a variable name mean in C#?

  What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

protected void Method1(Type1 @arg1, Type2 arg2)
...

I use c# with .net 3.5.

Thanks.


问:
Unexpected token import - jsfiddle
I am trying to make the toastr library work in jsfiddle but I keep getting this error: Uncaught SyntaxError: Unexpected token import

This is my jsfiddle: https://jsfiddle.net/50wL7mdz/77255/

This is my code:

```<code>import VueToastr from '@deveodk/vue-toastr';
Vue.use(VueToastr, {
    defaultPosition: 'toast-bottom-left',
    defaultType: 'info',
    defaultTimeout: 1000
});
new Vue({
  el: '#app',
  data: {
  },
  created(){
    this.$toastr('success', 'it works!', 'Yeahh');
  },
  methods: {
  }
})
</code>```

and this is the library reference: https://github.com/Deveodk/vue-toastr

Does import keyword not work in jsfiddle?

答:
Imports does not work on JSFIDDLE. You need to install the package and refer using import, which is not supported. Instead you can do this,

You can refer the library using external url,

```<code>https://unpkg.com/vue-toastr-2@0.0.8/dist/vue-toastr-2.js
https://unpkg.com/vue-toastr-2/dist/vue-toastr-2.min.css
</code>```

DEMO

Title: Unexpected token import - jsfiddle

Body:
I am trying to make the toastr library work in jsfiddle but I keep getting this error: Uncaught SyntaxError: Unexpected token import

This is my jsfiddle: https://jsfiddle.net/50wL7mdz/77255/

This is my code:

import VueToastr from '@deveodk/vue-toastr';
Vue.use(VueToastr, {
    defaultPosition: 'toast-bottom-left',
    defaultType: 'info',
    defaultTimeout: 1000
});
new Vue({
  el: '#app',
  data: {
  },
  created(){
    this.$toastr('success', 'it works!', 'Yeahh');
  },
  methods: {
  }
})

and this is the library reference: https://github.com/Deveodk/vue-toastr

Does import keyword not work in jsfiddle?

Body:
Imports does not work on JSFIDDLE. You need to install the package and refer using import, which is not supported. Instead you can do this,

You can refer the library using external url,

https://unpkg.com/vue-toastr-2@0.0.8/dist/vue-toastr-2.js
https://unpkg.com/vue-toastr-2/dist/vue-toastr-2.min.css

DEMO


问:
Is there a react-native checkbox example?
Are there any simple examples of implementing a react-native CheckBox? Facebook does not provided any examples. The CheckBox component that I am referring to can be found in the documentation here: http://facebook.github.io/react-native/docs/checkbox.html</p>

答:
Currently, the CheckBox component is only supported on Android as it is stated here. You should use the Switch component for iOS.

For Android, usage is pretty straight forward:

```<code><View style={{ flexDirection: 'column'}}>
  <CheckBox />
  <View style={{ flexDirection: 'row' }}>
    <CheckBox
      value={this.state.checked}
      onValueChange={() => this.setState({ checked: !this.state.checked })}
    />
    <Text style={{marginTop: 5}}> this is checkbox</Text>
  </View>
</View>
</code>```

View and Text components are optional, just to show how CheckBox can be used along with those.
Code above will produce this screen on Android device:

This is how the above code appears on an iOS device:

ContentLicense: CC BY-SA 4.0

Body:
Currently, the CheckBox component is only supported on Android as it is stated here. You should use the Switch component for iOS.

For Android, usage is pretty straight forward:

<View style={{ flexDirection: 'column'}}>
  <CheckBox />
  <View style={{ flexDirection: 'row' }}>
    <CheckBox
      value={this.state.checked}
      onValueChange={() => this.setState({ checked: !this.state.checked })}
    />
    <Text style={{marginTop: 5}}> this is checkbox</Text>
  </View>
</View>

View and Text components are optional, just to show how CheckBox can be used along with those.
Code above will produce this screen on Android device:

This is how the above code appears on an iOS device:


问:
Can I use bindParam always?
I see so many people using "execute(array [...]" in their SQL methods, I always used

execute->bindParam('[...]', $string);

Can I still using bindParam? If no, when should I use it? Thanks

答: Yes you should, it helps you dealing with unwanted quotes issues when adding rich text data and help you to prevent SQL Injection attack</p>

Title: Can I use bindParam always?


问:
How to check if a username exists in a text file via File/FileWriter/Scanner classes
I'm not sure what I'm doing wrong because after running the program in my main class, it completely skips over the

```<code>while(usernameCheck.hasNext()){
    //code...
}
</code>```

loop even though I purposely put a username that's already in my "accounts.txt" file. I also tried the contains() method but obviously if I put lets say "John1" and "John" is already in my accounts.txt file, it won't accept it

```<code>import java.util.Scanner;
import java.io.*;

public class CreateAccount {

public static void newAccount() throws IOException{

    Scanner keyboard = new Scanner(System.in);
    FileWriter fw = new FileWriter("accounts.txt",true);
    PrintWriter pw = new PrintWriter(fw);

    System.out.println("Please enter a username: ");
    String user = keyboard.nextLine();

    File file = new File("accounts.txt");
    Scanner usernameCheck = new Scanner(file);

    while(usernameCheck.hasNext()){
        String existingUsername = usernameCheck.nextLine();

        if(user.equalsIgnoreCase(existingUsername)){

            System.out.println("Username already exists");
            System.out.println("Please enter a username: ");
            user = keyboard.nextLine();
        }
    }

    System.out.println("Please enter a password: ");
    String pass = keyboard.nextLine();

    System.out.println("Account created!");
</code>```

*** After reading my code I realize I also have another problem: Even if I do create a username that doesn't exist in my "accounts.txt" class, it'll keep repeating the prompt that a username already exists because of the hasNext() method. What can I do about this?

答:
The difference between the code shown below and your code is quite evident. The prompts to the User are enclosed within while loop blocks for at least two reasons:

If the User enters a User Name that is already contained within the accounts.txt file then the User can be informed of such and be given the opportunity to enter another User Name. The same applies to the Password prompt. If an invalid Password is provided (like nothing) then the User is informed and given the opportunity to enter a valid Password.

To ensure the User actually enters a User Name or a Password.

These of course have nothing to do with file writing but does enhance options to the User so as to ensure there is actually something to write to file.

To read the accounts.txt file, the Scanner.hasNextLine() method is used instead of the Scanner.hasNext() method and here is why:

The Scanner.hasNext() method is written to work with the Scanner.next() method and the Scanner.hasNextLine() method is written to work with the Scanner.nextLine() method.

The Scanner.next() method works with whatever delimiter is used as your token separator. By default Scanner uses whitespace as a token separator, so, if reading for a User Name which could have a First and Last name separated by a whitespace this would provide 2 tokens (First Name and Last Name) which means you would need to make 2 calls to the Scanner.next() method to get the full User Name (one for each word). Think what is required now if there is a blank line in file or a space in front of the User Name in file.

The Scanner.nextLine() method however reads a complete file line of text, so it would read the User Name from file all in one call. You will also notice that I've also applied the String.trim() method to the end of the Scanner.nextLine() method:

String existingUsername = usernameCheck.nextLine().trim();

This is done so as to remove any leading or trailing tabs or white-spaces from the file line should there be any. We can do this since the Scanner.nextLine() method returns a String. Oh...Using the Scanner.hasNext() method could be why your loop is getting skipped over.

A mechanism has also been placed in code to allow the User to exit the newAccount() method at the "Enter User Name" prompt. If the letter q is supplied at this prompt then the the method is exited with a return; statement.

As mentioned earlier, the Password prompt has also been placed within a while loop so that validation of sorts can be done. Currently only a check that the Password actually contains something is done, this can however be expanded to cover whatever Password type validation you like. Perhaps a Password of a specific length, containing specific character types, etc.

Here is the code:

```<code>public static void newAccount() throws IOException {
    Scanner keyboard = new Scanner(System.in);
    File file = new File("accounts.txt");
    FileWriter fw = new FileWriter(file, true);
    Scanner usernameCheck = new Scanner(file);
    String user = "";
    while (user.equals("")) {
        System.out.println("Please enter a User name (q to exit): ");
        user = keyboard.nextLine().trim();
        if (user.toLowerCase().equals("q")) {
            System.out.println("User Exit!");
            return;  // exit the method.
        }
        while (usernameCheck.hasNextLine()) {
            String existingUsername = usernameCheck.nextLine().trim();
            if (user.equalsIgnoreCase(existingUsername)) {
                System.err.println("Username already exists! Try Again.\n");
                user = "";
                break;
            }
        }
    }
    usernameCheck.close(); // Close the Scanner file object
    String pass = "";
    while (pass.equals("")) {
        System.out.println("Please enter a password for " + user + ": ");
        pass = keyboard.nextLine();
        if (pass.equals("")) {
            System.err.println("Invalid Password! Try Again.\n");
        }
    }

    fw.write(user + System.lineSeparator());
    fw.write(pass + System.lineSeparator());
    fw.close(); // close the FileWriter object.

    System.out.println("Account created!");
}
</code>```

Body:
I'm not sure what I'm doing wrong because after running the program in my main class, it completely skips over the

while(usernameCheck.hasNext()){
    //code...
}

loop even though I purposely put a username that's already in my "accounts.txt" file. I also tried the contains() method but obviously if I put lets say "John1" and "John" is already in my accounts.txt file, it won't accept it

import java.util.Scanner;
import java.io.*;

public class CreateAccount {

public static void newAccount() throws IOException{

    Scanner keyboard = new Scanner(System.in);
    FileWriter fw = new FileWriter("accounts.txt",true);
    PrintWriter pw = new PrintWriter(fw);

    System.out.println("Please enter a username: ");
    String user = keyboard.nextLine();

    File file = new File("accounts.txt");
    Scanner usernameCheck = new Scanner(file);

    while(usernameCheck.hasNext()){
        String existingUsername = usernameCheck.nextLine();

        if(user.equalsIgnoreCase(existingUsername)){

            System.out.println("Username already exists");
            System.out.println("Please enter a username: ");
            user = keyboard.nextLine();
        }
    }

    System.out.println("Please enter a password: ");
    String pass = keyboard.nextLine();

    System.out.println("Account created!");

*** After reading my code I realize I also have another problem: Even if I do create a username that doesn't exist in my "accounts.txt" class, it'll keep repeating the prompt that a username already exists because of the hasNext() method. What can I do about this?

Body:
The difference between the code shown below and your code is quite evident. The prompts to the User are enclosed within while loop blocks for at least two reasons:

If the User enters a User Name that is already contained within the accounts.txt file then the User can be informed of such and be given the opportunity to enter another User Name. The same applies to the Password prompt. If an invalid Password is provided (like nothing) then the User is informed and given the opportunity to enter a valid Password.

To ensure the User actually enters a User Name or a Password.

These of course have nothing to do with file writing but does enhance options to the User so as to ensure there is actually something to write to file.

To read the accounts.txt file, the Scanner.hasNextLine() method is used instead of the Scanner.hasNext() method and here is why:

The Scanner.hasNext() method is written to work with the Scanner.next() method and the Scanner.hasNextLine() method is written to work with the Scanner.nextLine() method.

The Scanner.next() method works with whatever delimiter is used as your token separator. By default Scanner uses whitespace as a token separator, so, if reading for a User Name which could have a First and Last name separated by a whitespace this would provide 2 tokens (First Name and Last Name) which means you would need to make 2 calls to the Scanner.next() method to get the full User Name (one for each word). Think what is required now if there is a blank line in file or a space in front of the User Name in file.

The Scanner.nextLine() method however reads a complete file line of text, so it would read the User Name from file all in one call. You will also notice that I've also applied the String.trim() method to the end of the Scanner.nextLine() method:

String existingUsername = usernameCheck.nextLine().trim();

This is done so as to remove any leading or trailing tabs or white-spaces from the file line should there be any. We can do this since the Scanner.nextLine() method returns a String. Oh...Using the Scanner.hasNext() method could be why your loop is getting skipped over.

A mechanism has also been placed in code to allow the User to exit the newAccount() method at the "Enter User Name" prompt. If the letter q is supplied at this prompt then the the method is exited with a return; statement.

As mentioned earlier, the Password prompt has also been placed within a while loop so that validation of sorts can be done. Currently only a check that the Password actually contains something is done, this can however be expanded to cover whatever Password type validation you like. Perhaps a Password of a specific length, containing specific character types, etc.

Here is the code:

public static void newAccount() throws IOException {
    Scanner keyboard = new Scanner(System.in);
    File file = new File("accounts.txt");
    FileWriter fw = new FileWriter(file, true);
    Scanner usernameCheck = new Scanner(file);
    String user = "";
    while (user.equals("")) {
        System.out.println("Please enter a User name (q to exit): ");
        user = keyboard.nextLine().trim();
        if (user.toLowerCase().equals("q")) {
            System.out.println("User Exit!");
            return;  // exit the method.
        }
        while (usernameCheck.hasNextLine()) {
            String existingUsername = usernameCheck.nextLine().trim();
            if (user.equalsIgnoreCase(existingUsername)) {
                System.err.println("Username already exists! Try Again.\n");
                user = "";
                break;
            }
        }
    }
    usernameCheck.close(); // Close the Scanner file object
    String pass = "";
    while (pass.equals("")) {
        System.out.println("Please enter a password for " + user + ": ");
        pass = keyboard.nextLine();
        if (pass.equals("")) {
            System.err.println("Invalid Password! Try Again.\n");
        }
    }

    fw.write(user + System.lineSeparator());
    fw.write(pass + System.lineSeparator());
    fw.close(); // close the FileWriter object.

    System.out.println("Account created!");
}


问:
How to get binary representation of floating-point number in PHP?
Is there any way to get the binary representation of a floating point number in PHP? Something like Java's Double.doubleToRawLongBits().

Given a positive floating point number, I'd like to get the largest representable floating-point number which is less than that number. In Java, I can do it like this:

```<code>double x = Double.longBitsToDouble(Double.doubleToRawLongBits(d) - 1);
</code>```

But I'm not seeing anything similar in PHP.

答:
Here is a solution I came up with using Peter Bailey's suggestion. It requires 64-bit version of PHP. I don't claim this to be production-quality in any way, but I'm sharing in case anyone wants to build upon it. (In fact I ended up doing something different entirely after I posted the question, but I leave it here as an intellectual exercise.)</p>

```<code>// Returns the largest double-precision floating-point number which
// is less than the given value. Only works for positive values.
// Requires integers to be represented internally with 64 bits (on Linux
// this usually means you're on 64-bit OS with PHP built for 64-bit OS).
// Also requires 64-bit double-precision floating point numbers, but I
// think this is the case pretty much everywhere.
// Returns false on error.
function prevDouble($d) {
  $INT32_MASK = 0xffffffff;
  if((0x1deadbeef >> 32) !== 1) {
    echo 'error: only works on 64-bit systems!';
    return false;
  }
  if($d <= 0) {
    return false;
  }
  $beTest = bin2hex(pack('d', 1.0)); //test for big-endian
  if(strlen($beTest) != 16) {
    echo 'error: system does not use 8 bytes for double precision!';
    return false;
  }

  if($beTest == '3ff0000000000000') {
    $isBE = true;
  }
  else if($beTest == '000000000000f03f') {
    $isBE = false;
  }
  else {
    echo 'error: could not determine endian mode!';
    return false;
  }

  $bin = pack('d', $d);

  //convert to 64-bit int
  $int = 0;
  for($i = 0; $i < 8; $i++)
    $int = ($int << 8) | ord($bin[$isBE ? $i : 7 - $i]);

  $int--;
  //convert back to double
  if($isBE)
    $out = unpack('d', pack('N', ($int >> 32) & $INT32_MASK) . pack('N', $int & $INT32_MASK));
  else
    $out = unpack('d', pack('V', $int & $INT32_MASK) . pack('V', ($int >> 32) & $INT32_MASK));

  return $out[1];
}
</code>```

Body:
Is there any way to get the binary representation of a floating point number in PHP? Something like Java's Double.doubleToRawLongBits().

Given a positive floating point number, I'd like to get the largest representable floating-point number which is less than that number. In Java, I can do it like this:

double x = Double.longBitsToDouble(Double.doubleToRawLongBits(d) - 1);

But I'm not seeing anything similar in PHP.

Body:
Here is a solution I came up with using Peter Bailey's suggestion. It requires 64-bit version of PHP. I don't claim this to be production-quality in any way, but I'm sharing in case anyone wants to build upon it. (In fact I ended up doing something different entirely after I posted the question, but I leave it here as an intellectual exercise.)

// Returns the largest double-precision floating-point number which
// is less than the given value. Only works for positive values.
// Requires integers to be represented internally with 64 bits (on Linux
// this usually means you're on 64-bit OS with PHP built for 64-bit OS).
// Also requires 64-bit double-precision floating point numbers, but I
// think this is the case pretty much everywhere.
// Returns false on error.
function prevDouble($d) {
  $INT32_MASK = 0xffffffff;
  if((0x1deadbeef >> 32) !== 1) {
    echo 'error: only works on 64-bit systems!';
    return false;
  }
  if($d <= 0) {
    return false;
  }
  $beTest = bin2hex(pack('d', 1.0)); //test for big-endian
  if(strlen($beTest) != 16) {
    echo 'error: system does not use 8 bytes for double precision!';
    return false;
  }

  if($beTest == '3ff0000000000000') {
    $isBE = true;
  }
  else if($beTest == '000000000000f03f') {
    $isBE = false;
  }
  else {
    echo 'error: could not determine endian mode!';
    return false;
  }

  $bin = pack('d', $d);

  //convert to 64-bit int
  $int = 0;
  for($i = 0; $i < 8; $i++)
    $int = ($int << 8) | ord($bin[$isBE ? $i : 7 - $i]);

  $int--;
  //convert back to double
  if($isBE)
    $out = unpack('d', pack('N', ($int >> 32) & $INT32_MASK) . pack('N', $int & $INT32_MASK));
  else
    $out = unpack('d', pack('V', $int & $INT32_MASK) . pack('V', ($int >> 32) & $INT32_MASK));

  return $out[1];
}


问:
In a fragment if I press back button go to SettingsActivity.class
I have a activity_settings.xml file like below in this file I have 3 text views if I click one it will take me to a fragment

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.crowderia.chat.SettingsActivity"
    android:background="@color/black">

    <TextView
        android:id="@+id/tv_added_me"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Added Me" />

    <TextView
        android:id="@+id/tv_add_friends"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Friends" />

    <TextView
        android:id="@+id/tv_my_friends"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My Friends" />

    <FrameLayout
        android:id="@+id/settings_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

</RelativeLayout>
</code>```

My SettingsActivity.class like below

onclick event for each text view

```<code>tv_added_me.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setFragment(new AddedMeFragment());
            }
        });
</code>```

set fragment method

```<code>public void setFragment(Fragment f) {

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
        fragmentTransaction.replace(R.id.settings_fragment, f);
        fragmentTransaction.commit();
    }
</code>```

If I click each text view it will take me to each fragment but after I click back its not going to go to Settings Activity how can I make this work

Please help me Im new to these stuff

答:
You should remove all the fragments from FragmentManager on the click of back button.

```<code>FragmentManager fm = getSupportFragmentManager();
for (Fragment f : fm.getFragments()) {
    fm.beginTransaction().remove(f).commit();
}
</code>```

Body:
I have a activity_settings.xml file like below in this file I have 3 text views if I click one it will take me to a fragment

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.crowderia.chat.SettingsActivity"
    android:background="@color/black">

    <TextView
        android:id="@+id/tv_added_me"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Added Me" />

    <TextView
        android:id="@+id/tv_add_friends"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Friends" />

    <TextView
        android:id="@+id/tv_my_friends"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My Friends" />

    <FrameLayout
        android:id="@+id/settings_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

</RelativeLayout>

My SettingsActivity.class like below

onclick event for each text view

tv_added_me.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setFragment(new AddedMeFragment());
            }
        });

set fragment method

public void setFragment(Fragment f) {

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
        fragmentTransaction.replace(R.id.settings_fragment, f);
        fragmentTransaction.commit();
    }

If I click each text view it will take me to each fragment but after I click back its not going to go to Settings Activity how can I make this work

Please help me Im new to these stuff

Body:
You should remove all the fragments from FragmentManager on the click of back button.

FragmentManager fm = getSupportFragmentManager();
for (Fragment f : fm.getFragments()) {
    fm.beginTransaction().remove(f).commit();
}


问:
Mapbox GL: Get Layer IDs
I have a map with a few dozen layers, each with a unique ID. I have checkboxes to turn the layers on and off, for which I need a single array of all the layer IDs. I can't figure out how to loop through all of the map layers to capture the layer IDs. I tried using map.getLayer() but this returns the layer as an object, not the layer ID as a string. I want to loop through all of the map layers and push the layer ID strings to a new array. How do I do this?

```<code>mapboxgl.accessToken = "myaccesstoken";

var map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mymapboxstyle",
center: [-71.0664, 42.358],
minZoom: 14 //
});

map.on("style.load", function () {

map.addSource("contours", {
    type: "vector",
    url: "mapbox://mapbox.mapbox-terrain-v2"
    });

map.addSource("hDistricts-2017", {
    "type": "vector",
    "url": "mapbox://mysource"
    });

map.addLayer({
    "id": "contours",
    "type": "line",
    "source": "contours",
    "source-layer": "contour",
    "layout": {
        "visibility": "none",
        "line-join": "round",
        "line-cap": "round"
        },
    "paint": {
        "line-color": "#877b59",
        "line-width": 1
        }
     });

map.addLayer({
    "id": "Back Bay Architectural District",
    "source": "hDistricts-2017",
    "source-layer": "Boston_Landmarks_Commission_B-7q48wq",
    "type": "fill",
    "layout": {
        "visibility": "none"
        },
    "filter": ["==", "OBJECTID", 13],
    "paint": {
        "fill-color": "#192E39",
        "fill-outline-color": "#000000",
        "fill-opacity": 0.5
        }
    });

});

var layerIds = [];

function getIds() {

  //here I need to iterate through map layers to get id strings.
  //how do I do this???

 layerIds.push(    ); //then push those ids to new array.

 console.log(layerIds); //["contours", "Back Bay Architectural District"]

}
</code>```

答:
If kielni answer isn't convenient because of unknown reason, use map.getStyle().layers to get an array of object layers then map it to get an array of string ids.

```<code>var layers = map.getStyle().layers;

var layerIds = layers.map(function (layer) {
    return layer.id;
});
</code>```

Title: Mapbox GL: Get Layer IDs

Body:
I have a map with a few dozen layers, each with a unique ID. I have checkboxes to turn the layers on and off, for which I need a single array of all the layer IDs. I can't figure out how to loop through all of the map layers to capture the layer IDs. I tried using map.getLayer() but this returns the layer as an object, not the layer ID as a string. I want to loop through all of the map layers and push the layer ID strings to a new array. How do I do this?

mapboxgl.accessToken = "myaccesstoken";

var map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mymapboxstyle",
center: [-71.0664, 42.358],
minZoom: 14 //
});

map.on("style.load", function () {

map.addSource("contours", {
    type: "vector",
    url: "mapbox://mapbox.mapbox-terrain-v2"
    });

map.addSource("hDistricts-2017", {
    "type": "vector",
    "url": "mapbox://mysource"
    });

map.addLayer({
    "id": "contours",
    "type": "line",
    "source": "contours",
    "source-layer": "contour",
    "layout": {
        "visibility": "none",
        "line-join": "round",
        "line-cap": "round"
        },
    "paint": {
        "line-color": "#877b59",
        "line-width": 1
        }
     });

map.addLayer({
    "id": "Back Bay Architectural District",
    "source": "hDistricts-2017",
    "source-layer": "Boston_Landmarks_Commission_B-7q48wq",
    "type": "fill",
    "layout": {
        "visibility": "none"
        },
    "filter": ["==", "OBJECTID", 13],
    "paint": {
        "fill-color": "#192E39",
        "fill-outline-color": "#000000",
        "fill-opacity": 0.5
        }
    });

});

var layerIds = [];

function getIds() {

  //here I need to iterate through map layers to get id strings.
  //how do I do this???

 layerIds.push(    ); //then push those ids to new array.

 console.log(layerIds); //["contours", "Back Bay Architectural District"]

}

Body:
If kielni answer isn't convenient because of unknown reason, use map.getStyle().layers to get an array of object layers then map it to get an array of string ids.

var layers = map.getStyle().layers;

var layerIds = layers.map(function (layer) {
    return layer.id;
});


问:
Rails serialization error for async geocoding with ahoy gem using mongoid
I have a Rails 5 app, running both a postgresql DB for application data and MongoDB (mongoid) for analytics, generated by the fantastic ahoy gem.

Everything works great until I switch to asynchronous geocoding in config/initializers/ahoy.rb, which generates the error below:

```<code>ActiveJob::SerializationError (Unsupported argument type: Visit):
</code>```

The app is using delayed_job, for background processing.

I there a workaround for this issue, or is this caused by incompatibility between mongoid and delayed_job?

答:
Try adding the GlobalId mixin to your model</p>

```<code>class Visit
  include GlobalID::Identification
end
</code>```

Body:
I have a Rails 5 app, running both a postgresql DB for application data and MongoDB (mongoid) for analytics, generated by the fantastic ahoy gem.

Everything works great until I switch to asynchronous geocoding in config/initializers/ahoy.rb, which generates the error below:

ActiveJob::SerializationError (Unsupported argument type: Visit):

The app is using delayed_job, for background processing.

I there a workaround for this issue, or is this caused by incompatibility between mongoid and delayed_job?

Body:
Try adding the GlobalId mixin to your model

class Visit
  include GlobalID::Identification
end


问:
how to create new Asp.Net_SessionId in asp.net
I want to create new Asp.Net_SessionId whenever user LoggedIn to my system. How can i create it and if i cannot create it then what may be the approach to update Asp.Net_SessionId value,  I means should i save Guid.NewGuid() in Asp.Net_SessionId to create a new value of Asp.Net_SessionId</p>

答:
To override the session ID, you have to create a custom session provider, not an easy task and not something I'd recommend getting into.  Why create the user a session ID?  If you want to give them a unique ID, then create your own guid identifier and store it in session, and refer to this for your own personal needs...

HTH.


问:
Find the value property of an object that is inside of a linked list, using recursive function
This is a JavaScript practice exercise.

Suppose I have a linked list object as follow:

```<code>   var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}
</code>```

I need to write a recursive method to find the value of a certain sub-listed object.

For example, the method "nth":

```<code>   console.log(nth(list, 1));
</code>```

Should return value 20.

This is easy to accomplish if I change it to an array first.

However, I cannot change it to an array, the method "nth" has to be recursive.

If my method has to eventually return the value property, how do I make it recursive to the next sub-list? Doesn't the method has to return the next linked list in order to get to the object I desire?

Here's a hint that the question gave:

The recursive version of nth will, similarly, look at an ever smaller part of the “tail” of the list and at the same time count down the index until it reaches zero, at which point it can return the value property of the node it is looking at. To get the zeroeth element of a list, you simply take the value property of its head node. To get element N + 1, you take the Nth element of the list that’s in this list’s rest property.

答:
think the key to solve this method recursively is to call the parent method until the input parameter become one</p>

```<code>nth(list, index) {
    if(list == null) return -1;
    if(index == 0) return list.value;
    nth(list.rest, index-1);
}
</code>```

Body:
This is a JavaScript practice exercise.

Suppose I have a linked list object as follow:

   var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}

I need to write a recursive method to find the value of a certain sub-listed object.

For example, the method "nth":

   console.log(nth(list, 1));

Should return value 20.

This is easy to accomplish if I change it to an array first.

However, I cannot change it to an array, the method "nth" has to be recursive.

If my method has to eventually return the value property, how do I make it recursive to the next sub-list? Doesn't the method has to return the next linked list in order to get to the object I desire?

Here's a hint that the question gave:

The recursive version of nth will, similarly, look at an ever smaller part of the “tail” of the list and at the same time count down the index until it reaches zero, at which point it can return the value property of the node it is looking at. To get the zeroeth element of a list, you simply take the value property of its head node. To get element N + 1, you take the Nth element of the list that’s in this list’s rest property.

Body:
think the key to solve this method recursively is to call the parent method until the input parameter become one

nth(list, index) {
    if(list == null) return -1;
    if(index == 0) return list.value;
    nth(list.rest, index-1);
}


问:
How to stop printing the same value twice in prolog?
I have this facts or database in prolog to see if the educations is the same or less than.  for example highschool <= highschool is true and highschool <= phd is true too, but masters <= highschool is false.

```<code>edu_less(high_school, bachelor).
edu_less(bachelor, masters).
edu_less(masters, phd).

edu_lessOrEqual(X,X).
edu_lessOrEqual(X, Y):- edu_less(X,Y).
edu_lessOrEqual(X, Y):- edu_less(X,Z),
                        edu_lessOrEqual(Z,Y).
</code>```

but this outputs

```<code>edu_lessOrEqual(masters, phd).
true;
true;
false.
</code>```

when i want only one true to be printed in the output.

```<code>true;
false.
</code>```

答: Basically, it's because in the third clause of edu_lessOrEqual/2, you recursively call edu_lessOrEqual/2, so you wind up with a case where Z and Y are both instantiated to phd (phd is in fact equal to phd so it fulfills the logic you have spelled out). You can correct it by adding a Z \= Y on the end of the third clause, but this is a situation where I would be tempted to use a conditional statement just to make sure I don't wind up with useless choice points.

Body:
I have this facts or database in prolog to see if the educations is the same or less than.  for example highschool <= highschool is true and highschool <= phd is true too, but masters <= highschool is false.

edu_less(high_school, bachelor).
edu_less(bachelor, masters).
edu_less(masters, phd).

edu_lessOrEqual(X,X).
edu_lessOrEqual(X, Y):- edu_less(X,Y).
edu_lessOrEqual(X, Y):- edu_less(X,Z),
                        edu_lessOrEqual(Z,Y).

but this outputs

edu_lessOrEqual(masters, phd).
true;
true;
false.

when i want only one true to be printed in the output.

true;
false.


问:
incresing counter in a recursive function
I have a question about the functionality of increasing values within a recursive function.

When I use:

counter++ does not work

But when i use counter + 1 It works correctly.

I also found another way for it to work: ++counter, but I really could not understand what a difference it is to use the ++ before the counter.

Example:

```<code>printEachName = (companyNames, newPeople, counter, callback) => {
  if (companyNames.length === newPeople.length) {
    return callback(false, companyNames);
  }
  console.log('counter >>> ', counter);
  let newP = newPeople[counter];

  companyNames.push(newP.name);
  printEachName(companyNames, newPeople, counter + 1, callback);
}

printEachName([], newPeople, 0, (errorPrinting, response) => {
  if (errorPrinting) {
    //res.send()
    return;
  }

  console.log('response is >>> ', response);
});
</code>```

答: Try ++counter. Using a prefix increment operator will first increment the variable then pass it to the function. Do note this is different from counter + 1 which does not change its value.

Body:
I have a question about the functionality of increasing values within a recursive function.

When I use:

counter++ does not work

But when i use counter + 1 It works correctly.

I also found another way for it to work: ++counter, but I really could not understand what a difference it is to use the ++ before the counter.

Example:

printEachName = (companyNames, newPeople, counter, callback) => {
  if (companyNames.length === newPeople.length) {
    return callback(false, companyNames);
  }
  console.log('counter >>> ', counter);
  let newP = newPeople[counter];

  companyNames.push(newP.name);
  printEachName(companyNames, newPeople, counter + 1, callback);
}

printEachName([], newPeople, 0, (errorPrinting, response) => {
  if (errorPrinting) {
    //res.send()
    return;
  }

  console.log('response is >>> ', response);
});


答: This probably has been already answered, but a++ takes the value a and use it and then increment the value. On the other hand ++a increments the value of a first and then use the incremented value (equivalent to a + 1 in your particular example).

Title: incresing counter in a recursive function


答:
This is because counter++, ++counter and counter + 1 are three completely different things.

Explained with examples:

```<code>function f(n) { console.log(n); }
var counter = 0;

// Call f(counter) and then increment counter after
f(counter++);
// log: 0
// counter: 1

// Increment counter and then call f(counter)
f(++counter);
// log: 2
// counter: 2

// Call f() with the value counter+1, do not alter counter
f(counter + 1);
// log: 3
// counter: 2
</code>```

The + 1 approach works because you're correctly supplying the incremented value to the function call. The prefix increment would work as well, but as counter is not used anywhere else this just over-complicates things. The postfix version is never going to work.

Body:
This is because counter++, ++counter and counter + 1 are three completely different things.

Explained with examples:

function f(n) { console.log(n); }
var counter = 0;

// Call f(counter) and then increment counter after
f(counter++);
// log: 0
// counter: 1

// Increment counter and then call f(counter)
f(++counter);
// log: 2
// counter: 2

// Call f() with the value counter+1, do not alter counter
f(counter + 1);
// log: 3
// counter: 2

The + 1 approach works because you're correctly supplying the incremented value to the function call. The prefix increment would work as well, but as counter is not used anywhere else this just over-complicates things. The postfix version is never going to work.


问:
User Defined Function to create and sum a subset in R
I need help defining a function that creates a vector in a database where, for each row, the function looks at another column in that database, searches for that value in a designated column of a separate database, creates a subset of that second database consisting of all matching rows, sums a separate column of that new subset, and returns that value to the corresponding row of the new column in the original database.

In other words, I have a data frame that looks something like this:

```<code>ID <- c('a', 'b', 'c', 'd', 'e')
M <- 20:39
df <- data.frame(cbind(ID, M))
df$M <- as.numeric(df$M)
> df
   ID  M
1   a  1
2   b  2
3   c  3
4   d  4
5   e  5
6   a  6
7   b  7
8   c  8
9   d  9
10  e 10
11  a 11
12  b 12
13  c 13
14  d 14
15  e 15
16  a 16
17  b 17
18  c 18
19  d 19
20  e 20
> str(df)
'data.frame':   20 obs. of  2 variables:
 $ ID: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5 1 2 3 4 5 ...
 $ M : num  1 2 3 4 5 6 7 8 9 10 ...
</code>```

I would like to create a new data frame, Z, such that Z <- data.frame(cbind(X, Y)) where:

```<code>X <- as.character(unique(df$ID))
> X
[1] "a" "b" "c" "d" "e"
</code>```

and Y is a vector of the sum of all a's, sum of all b's, sum of all c's, etc...

So, Y should be equal to c(34, 38, 42, 46, 50) and my final result should be:

```<code>> Z
  X  Y
1 a 34
2 b 38
3 c 42
4 d 46
5 e 50
> str(Z)
'data.frame':   5 obs. of  2 variables:
 $ X: chr  "a" "b" "c" "d" ...
 $ Y: num  34 38 42 46 50
</code>```

To do this, I've tried first turning X into a data frame (is it easier to work with as a data table?):

```<code>> Z <- data.frame(X)
> Z
  X
1 a
2 b
3 c
4 d
5 e
> str(Z)
'data.frame':   5 obs. of  1 variable:
 $ X: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
</code>```

and then defining Y as Z$Y <- sum(df[df$ID == Z$X, 2]) but I don't get unique values:

```<code>> Z
  X   Y
1 a 210
2 b 210
3 c 210
4 d 210
5 e 210
</code>```

I've also tried defining the function f1() like so:

```<code>f1 <- function(v, w, x, y, z){sum(v[v$w == x$y, z])}
</code>```

but that gets me:

```<code>> f1(df, 'ID', Z, 'X', 'M')
[1] 0
</code>```

I have found a function from another post on this forum that does something similar:

```<code>f1 <- function(df, cols, match_with, to_x = 50){
  df[cols] <- lapply(df[cols], function(i)
    ifelse(grepl(to_x, match_with, fixed = TRUE), 'MID',
           i))
  return(df)
}
</code>```

This looks for the value "50" in the match_with column and returns the value "MID" to that row of the column designated by cols, provided both columns in the same designated data base df. So, I would need to replace to_x = 50 with something that, instead of looking for the fixed value "50," looks for whatever value is in the column Z$X and, instead of returning the fixed value "MID," returns the sum of the values df[df$ID == Z$X, df$M]. I've attempted these changes myself by writing variations of the following:

```<code>f1 <- function(df, cols, match_with, to_x = df[ , 1], x){
  df[cols] <- lapply(df[cols], function(i)
    ifelse(grepl(to_x, match_with, fixed = TRUE), sum(x),
           i))
  return(df)
}
</code>```

but, so far, none of my variations have produced the desired results. This one gave me:

```<code>> f1(Z, df, cols = c('Y'), match_with = df$ID, x = df$M)
  X   Y
1 a 210
2 b 210
3 c 210
4 d 210
5 e 210
Warning messages:
1: In grepl(to_x, match_with, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used
2: In `[<-.data.frame`(`*tmp*`, cols, value = list(Y = c(210, 210,  :
  replacement element 1 has 20 rows to replace 5 rows
</code>```

It seems to be summing the entirety of df$M instead of the subsets where df$ID == Z$X. In other variations it seemed to have problems referencing a column in a second data frame.

I am somewhat new to R and have almost no experience writing user-defined functions (as you probably could tell by this question). Any help would be very much appreciated!

答:
Nevermind ya'll, I think I got it!</p>

```<code>> f1 <- function(col1, col2, df2, to_add){
+ lapply(col1, function(i){
+   df2$x <- grepl(i, col2, fixed = TRUE)
+   df3 <- df2[df2$x == TRUE, to_add]
+   sum(df3, na.rm = TRUE)
+ })}
> Z$Y <- f1(Z$X, df$ID, df, c('M'))
> Z
  X  Y
1 a 34
2 b 38
3 c 42
4 d 46
5 e 50
</code>```

Body:
I need help defining a function that creates a vector in a database where, for each row, the function looks at another column in that database, searches for that value in a designated column of a separate database, creates a subset of that second database consisting of all matching rows, sums a separate column of that new subset, and returns that value to the corresponding row of the new column in the original database.

In other words, I have a data frame that looks something like this:

ID <- c('a', 'b', 'c', 'd', 'e')
M <- 20:39
df <- data.frame(cbind(ID, M))
df$M <- as.numeric(df$M)
> df
   ID  M
1   a  1
2   b  2
3   c  3
4   d  4
5   e  5
6   a  6
7   b  7
8   c  8
9   d  9
10  e 10
11  a 11
12  b 12
13  c 13
14  d 14
15  e 15
16  a 16
17  b 17
18  c 18
19  d 19
20  e 20
> str(df)
'data.frame':   20 obs. of  2 variables:
 $ ID: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5 1 2 3 4 5 ...
 $ M : num  1 2 3 4 5 6 7 8 9 10 ...

I would like to create a new data frame, Z, such that Z <- data.frame(cbind(X, Y)) where:

X <- as.character(unique(df$ID))
> X
[1] "a" "b" "c" "d" "e"

and Y is a vector of the sum of all a's, sum of all b's, sum of all c's, etc...

So, Y should be equal to c(34, 38, 42, 46, 50) and my final result should be:

> Z
  X  Y
1 a 34
2 b 38
3 c 42
4 d 46
5 e 50
> str(Z)
'data.frame':   5 obs. of  2 variables:
 $ X: chr  "a" "b" "c" "d" ...
 $ Y: num  34 38 42 46 50

To do this, I've tried first turning X into a data frame (is it easier to work with as a data table?):

> Z <- data.frame(X)
> Z
  X
1 a
2 b
3 c
4 d
5 e
> str(Z)
'data.frame':   5 obs. of  1 variable:
 $ X: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5

and then defining Y as Z$Y <- sum(df[df$ID == Z$X, 2]) but I don't get unique values:

> Z
  X   Y
1 a 210
2 b 210
3 c 210
4 d 210
5 e 210

I've also tried defining the function f1() like so:

f1 <- function(v, w, x, y, z){sum(v[v$w == x$y, z])}

but that gets me:

> f1(df, 'ID', Z, 'X', 'M')
[1] 0

I have found a function from another post on this forum that does something similar:

f1 <- function(df, cols, match_with, to_x = 50){
  df[cols] <- lapply(df[cols], function(i)
    ifelse(grepl(to_x, match_with, fixed = TRUE), 'MID',
           i))
  return(df)
}

This looks for the value "50" in the match_with column and returns the value "MID" to that row of the column designated by cols, provided both columns in the same designated data base df. So, I would need to replace to_x = 50 with something that, instead of looking for the fixed value "50," looks for whatever value is in the column Z$X and, instead of returning the fixed value "MID," returns the sum of the values df[df$ID == Z$X, df$M]. I've attempted these changes myself by writing variations of the following:

f1 <- function(df, cols, match_with, to_x = df[ , 1], x){
  df[cols] <- lapply(df[cols], function(i)
    ifelse(grepl(to_x, match_with, fixed = TRUE), sum(x),
           i))
  return(df)
}

but, so far, none of my variations have produced the desired results. This one gave me:

> f1(Z, df, cols = c('Y'), match_with = df$ID, x = df$M)
  X   Y
1 a 210
2 b 210
3 c 210
4 d 210
5 e 210
Warning messages:
1: In grepl(to_x, match_with, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used
2: In `[<-.data.frame`(`*tmp*`, cols, value = list(Y = c(210, 210,  :
  replacement element 1 has 20 rows to replace 5 rows

It seems to be summing the entirety of df$M instead of the subsets where df$ID == Z$X. In other variations it seemed to have problems referencing a column in a second data frame.

I am somewhat new to R and have almost no experience writing user-defined functions (as you probably could tell by this question). Any help would be very much appreciated!

Body:
Nevermind ya'll, I think I got it!

> f1 <- function(col1, col2, df2, to_add){
+ lapply(col1, function(i){
+   df2$x <- grepl(i, col2, fixed = TRUE)
+   df3 <- df2[df2$x == TRUE, to_add]
+   sum(df3, na.rm = TRUE)
+ })}
> Z$Y <- f1(Z$X, df$ID, df, c('M'))
> Z
  X  Y
1 a 34
2 b 38
3 c 42
4 d 46
5 e 50