问:
Getting 400 bad request when I use "ValidateAntiForgeryToken" and "Authorize"
I'm using asp.net core in the server side and xamarin in the client side.I use JWT token and I want to validate forgery token at the same time.

This is my client side code :

 public async Task<string> PostAsync(object model, string url)
        {
            var cookieContainer = new CookieContainer();
            var handlerhttps = new HttpClientHandler
            {
                UseCookies = true,
                UseDefaultCredentials = true,
                CookieContainer = cookieContainer
            };

            var clientPage = new HttpClient(handler: handlerhttps)
            {
                BaseAddress = new Uri(uriString: Application.Current.Resources[index: "Domain"] + "/api/token")
            };

            var pageWithToken = await clientPage.GetAsync(requestUri: clientPage.BaseAddress);
            var verificationToken = await pageWithToken.Content.ReadAsStringAsync();
            using (var handler = new HttpClientHandler
            {
                CookieContainer = cookieContainer,
                UseDefaultCredentials = true,
                UseCookies = true
            })
            {
                using (var client = new HttpClient(handler: handler) {BaseAddress = new Uri(uriString: url)})
                {
                    client.DefaultRequestHeaders.Add(name: "RequestVerificationToken", value: verificationToken);
                    if (Application.Current.Properties[key: "Token"] != null)
                    {
                        var token = Application.Current.Properties[key: "Token"].ToString();
                        client.DefaultRequestHeaders.Authorization =
                            new AuthenticationHeaderValue(scheme: "Bearer", parameter: token);
                    }

                    var json = JsonConvert.SerializeObject(value: model);
                    var content = new StringContent(content: json, encoding: Encoding.UTF8,
                        mediaType: "application/json");
                    var response = await client.PostAsync(requestUri: client.BaseAddress, content: content);
                    var result = await response.Content.ReadAsStringAsync();
                    return result;
                }
            }
        }
```

My problem is when I use [ValidateAntiForgeryToken] and [Authorize] in the server side at the same time, I get 400 bad request.

But when I remove [ValidateAntiForgeryToken], It will authorize without any problem.

When I remove [Authorize] , I don't get 400 bad request and it validate forgery token successfully.

I don't know how to solve this problem.

答:
If you are using Microsoft.AspNetCore.Mvc.TagHelpers it will add a input field with a 'difficult to guess' code:

```<code><input name="__RequestVerificationToken" type="hidden" value="CfDJ8PXv-VNSuRBLvOlUgHlQcf4p8B29vW6EKn4ENesSgHR79kWTvbnQ9a1Taj90b-e66-79H7Nx5ljHnvPbwqfSNqHMRMaBkoRKGsTxtbZZlq0rSl2zbGK2aKpPQc0qnoNuRehSNhP097P5-Vlp-3OSPYdIqLQJSqIsPDaQsEOXsNU4qIIDrj-tIhqk5EW9tTYc6g">
</code>```

Anyways, even if you add @Html.AntiForgeryToken() it wouldn't conflict. However you cannot decorate the 'first' controller action with [ValidateAntiForgeryToken], only the final one with will get the POST.

Example:

Action 1

```<code>[HttpPost]
[AllowAnonymous]
[ActionName("SpecialSignUp")]
public IActionResult Index([FromForm] string email)
{
    // TODO : code in here
    return View(email);
}
</code>```

Users will be redirect to above action through a POST.

Let's say that the view above displays a form with the email field pre-filled and other fields to be filled.

If you decorate it with [ValidateAntiForgeryToken] you will get a 400 (Bad Request). Removing it, all will be fine.

Action 2

```<code>[HttpPost]
[AllowAnonymous] // It could be [Authorized]
[ActionName("SpecialSignUp")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LaunchSignUpAsync([FromForm] SpecialSignUpViewModel model)
{
    // TODO : Code in here
    return RedirectToAction("OtherActionX", data);
}
</code>```

Form will be posted by the above View

Now all it's working, no conflict is happening anymore. If you respect that sequence, it will work for you!

I had the same issue, and it was happening because I decorated the 'Action 1' with [ValidateAntiForgeryToken] as well.

Hopefully it helps!

Body:
I'm using asp.net core in the server side and xamarin in the client side.I use JWT token and I want to validate forgery token at the same time.

This is my client side code :

 public async Task<string> PostAsync(object model, string url)
        {
            var cookieContainer = new CookieContainer();
            var handlerhttps = new HttpClientHandler
            {
                UseCookies = true,
                UseDefaultCredentials = true,
                CookieContainer = cookieContainer
            };

            var clientPage = new HttpClient(handler: handlerhttps)
            {
                BaseAddress = new Uri(uriString: Application.Current.Resources[index: "Domain"] + "/api/token")
            };

            var pageWithToken = await clientPage.GetAsync(requestUri: clientPage.BaseAddress);
            var verificationToken = await pageWithToken.Content.ReadAsStringAsync();
            using (var handler = new HttpClientHandler
            {
                CookieContainer = cookieContainer,
                UseDefaultCredentials = true,
                UseCookies = true
            })
            {
                using (var client = new HttpClient(handler: handler) {BaseAddress = new Uri(uriString: url)})
                {
                    client.DefaultRequestHeaders.Add(name: "RequestVerificationToken", value: verificationToken);
                    if (Application.Current.Properties[key: "Token"] != null)
                    {
                        var token = Application.Current.Properties[key: "Token"].ToString();
                        client.DefaultRequestHeaders.Authorization =
                            new AuthenticationHeaderValue(scheme: "Bearer", parameter: token);
                    }

                    var json = JsonConvert.SerializeObject(value: model);
                    var content = new StringContent(content: json, encoding: Encoding.UTF8,
                        mediaType: "application/json");
                    var response = await client.PostAsync(requestUri: client.BaseAddress, content: content);
                    var result = await response.Content.ReadAsStringAsync();
                    return result;
                }
            }
        }

My problem is when I use [ValidateAntiForgeryToken] and [Authorize] in the server side at the same time, I get 400 bad request.

But when I remove [ValidateAntiForgeryToken], It will authorize without any problem.

When I remove [Authorize] , I don't get 400 bad request and it validate forgery token successfully.

I don't know how to solve this problem.

Body:
If you are using Microsoft.AspNetCore.Mvc.TagHelpers it will add a input field with a 'difficult to guess' code:

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8PXv-VNSuRBLvOlUgHlQcf4p8B29vW6EKn4ENesSgHR79kWTvbnQ9a1Taj90b-e66-79H7Nx5ljHnvPbwqfSNqHMRMaBkoRKGsTxtbZZlq0rSl2zbGK2aKpPQc0qnoNuRehSNhP097P5-Vlp-3OSPYdIqLQJSqIsPDaQsEOXsNU4qIIDrj-tIhqk5EW9tTYc6g">

Anyways, even if you add @Html.AntiForgeryToken() it wouldn't conflict. However you cannot decorate the 'first' controller action with [ValidateAntiForgeryToken], only the final one with will get the POST.

Example:

Action 1

[HttpPost]
[AllowAnonymous]
[ActionName("SpecialSignUp")]
public IActionResult Index([FromForm] string email)
{
    // TODO : code in here
    return View(email);
}

Users will be redirect to above action through a POST.

Let's say that the view above displays a form with the email field pre-filled and other fields to be filled.

If you decorate it with [ValidateAntiForgeryToken] you will get a 400 (Bad Request). Removing it, all will be fine.

Action 2

[HttpPost]
[AllowAnonymous] // It could be [Authorized]
[ActionName("SpecialSignUp")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LaunchSignUpAsync([FromForm] SpecialSignUpViewModel model)
{
    // TODO : Code in here
    return RedirectToAction("OtherActionX", data);
}

Form will be posted by the above View

Now all it's working, no conflict is happening anymore. If you respect that sequence, it will work for you!

I had the same issue, and it was happening because I decorated the 'Action 1' with [ValidateAntiForgeryToken] as well.

Hopefully it helps!


来源: stackexchange

问:
Hystrix fallback method does not run
I run a call to an endpoint that is off, however the hystrix does not execute the fallback method, and throws an exception:

```<code>java.util.concurrent.ExecutionException: org.springframework.web.client.ResourceAccessException:
I/O error on GET request for "http://localhost:8080/wallet/customers/100/cards/": Conexão recusada (Connection refused); nested exception is java.net.ConnectException: Conexão recusada (Connection refused)
</code>```

Anyone know if any configuration is missing?

My main

```<code>@EnableCircuitBreaker
@SpringBootApplication
public class WalletPaymentApplication {

    public static void main(String[] args) {
        SpringApplication.run(WalletPaymentApplication.class, args);
    }
}
</code>```

and my service:

```<code>public PaymentMethodsData setUpPaymentMethods(String customerId) {
    return new PaymentMethodsData(getCardList(customerId));
}

@HystrixCommand(fallbackMethod = "getCardListCircuitBreaker")
public List<SummaryCardData> getCardList(String customerId) {
    return template.getForObject(configureUrl(cardUrl), CardRows.class, customerId).getRows();
}

public List<SummaryCardData> getCardListCircuitBreaker(String customerId){
    return new ArrayList<>();
}
</code>```

答: To enable @HystrixCommand(fallbackMethod = "getCardListCircuitBreaker") you have to call your method from another bean. Then annotation will work properly.

ContentLicense: CC BY-SA 3.0

Title: Hystrix fallback method does not run

Body:
I run a call to an endpoint that is off, however the hystrix does not execute the fallback method, and throws an exception:

java.util.concurrent.ExecutionException: org.springframework.web.client.ResourceAccessException:
I/O error on GET request for "http://localhost:8080/wallet/customers/100/cards/": Conexão recusada (Connection refused); nested exception is java.net.ConnectException: Conexão recusada (Connection refused)

Anyone know if any configuration is missing?

My main

@EnableCircuitBreaker
@SpringBootApplication
public class WalletPaymentApplication {

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

and my service:

public PaymentMethodsData setUpPaymentMethods(String customerId) {
    return new PaymentMethodsData(getCardList(customerId));
}

@HystrixCommand(fallbackMethod = "getCardListCircuitBreaker")
public List<SummaryCardData> getCardList(String customerId) {
    return template.getForObject(configureUrl(cardUrl), CardRows.class, customerId).getRows();
}

public List<SummaryCardData> getCardListCircuitBreaker(String customerId){
    return new ArrayList<>();
}


问:
Class parameter syntax errors
I am trying to learn to write puppet modules in a good way, so I've started looking around for tutorials and howto.

I've seen that users suggest writing the main class in the following way, but It's actually failing for me.
I am honestly a bit confused how the 2 blocks between brackets are actually connected, and so I might be not seeing an obvious error or real missing comma.

I am running Puppet 3.8 by the way

```<code>class icinga2 {
    $version = 'present'
    $enable = true
    $start = true
} {
    class{'icinga2::install': } ->
    class{'icinga2::config': } ~>
    class{'icinga2::service': } ->
    Class["icinga2"]
}
</code>```

Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Syntax error at '{'; expected '}' at /etc/puppet/modules/icinga2/manifests/init.pp:5

答:
Your problem here is that your parameters must be surrounded by (), not {}. Also, they should be commas separated.</p>

```<code>class icinga2 (
    $version = 'present',
    $enable = true,
    $start = true,
) {
    class{'icinga2::install': } ->
    class{'icinga2::config': } ~>
    class{'icinga2::service': } ->
    Class["icinga2"]
}
</code>```

Title: Class parameter syntax errors

Body:
I am trying to learn to write puppet modules in a good way, so I've started looking around for tutorials and howto.

I've seen that users suggest writing the main class in the following way, but It's actually failing for me.
I am honestly a bit confused how the 2 blocks between brackets are actually connected, and so I might be not seeing an obvious error or real missing comma.

I am running Puppet 3.8 by the way

class icinga2 {
    $version = 'present'
    $enable = true
    $start = true
} {
    class{'icinga2::install': } ->
    class{'icinga2::config': } ~>
    class{'icinga2::service': } ->
    Class["icinga2"]
}

Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Syntax error at '{'; expected '}' at /etc/puppet/modules/icinga2/manifests/init.pp:5

Body:
Your problem here is that your parameters must be surrounded by (), not {}. Also, they should be commas separated.

class icinga2 (
    $version = 'present',
    $enable = true,
    $start = true,
) {
    class{'icinga2::install': } ->
    class{'icinga2::config': } ~>
    class{'icinga2::service': } ->
    Class["icinga2"]
}


问:
Push Notifications when app is closed
Do you know if is it possible to receive notifications from google cloud message when the application is fully closed?

I know if it's open or in background yes, but can it be programmed any way in order to receive them?

EDIT:

I continue without receiving notifications when the app is closed.

I attached the code in case I have an error and I am not watching it.

MANIFEST

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.frab"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.frab.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<permission
android:name="com.frab.permission.C2D_MESSAGE"
android:protectionLevel="signature" />

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.frab.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver
android:name=".GGMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.something" />
</intent-filter>
</receiver>

<service android:name=".GCMIntentService" />
</application>

</manifest>
</code>```

BROADCAST RECEIVER

```<code>package com.something;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.activities.SignIn;
import com.google.android.gcm.GCMBaseIntentService;
import com.objects.Globals;

public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GGM <-----> FRAB";
private Bundle extras;

public GCMIntentService() {
super(Globals.SENDER_ID);
}

@Override
public void onDestroy() {
Log.d(TAG, "terminando servicio");
}

@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
}

@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId = " + registrationId);
}
@Override
protected void onMessage(Context context, Intent data) {
extras = data.getExtras();
String message = extras.getString("msg");
Log.d("******", message);
sendNotification(message);
}

@Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId = " + errorId);
}
}

package com.something;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class GGMBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
</code>```

When the app is open : OK

When the app is in background : Ok

When the app is closed forcefully by the user : notifications don't arrive

What is the problem?

Thank you very much.

答:
After some testing I did on this issue, I found out that it behaves differently on how the app is closed. If you close the app while the cable is connected to the device, it then blocks every notification when the app is closed.
However, if you take the cable off the device and close the app, when you send the notification, everything works again, as it should!

In case you get a "Waiting for the Debugger" popup message, just restart the device and then send a test notification!

Title: Push Notifications when app is closed

Body:
Do you know if is it possible to receive notifications from google cloud message when the application is fully closed?

I know if it's open or in background yes, but can it be programmed any way in order to receive them?

EDIT:

I continue without receiving notifications when the app is closed.

I attached the code in case I have an error and I am not watching it.

MANIFEST

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.frab"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.frab.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<permission
android:name="com.frab.permission.C2D_MESSAGE"
android:protectionLevel="signature" />

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.frab.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver
android:name=".GGMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.something" />
</intent-filter>
</receiver>

<service android:name=".GCMIntentService" />
</application>

</manifest>

BROADCAST RECEIVER

package com.something;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.activities.SignIn;
import com.google.android.gcm.GCMBaseIntentService;
import com.objects.Globals;

public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GGM <-----> FRAB";
private Bundle extras;

public GCMIntentService() {
super(Globals.SENDER_ID);
}

@Override
public void onDestroy() {
Log.d(TAG, "terminando servicio");
}

@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
}

@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId = " + registrationId);
}
@Override
protected void onMessage(Context context, Intent data) {
extras = data.getExtras();
String message = extras.getString("msg");
Log.d("******", message);
sendNotification(message);
}

@Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId = " + errorId);
}
}

package com.something;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class GGMBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}

When the app is open : OK

When the app is in background : Ok

When the app is closed forcefully by the user : notifications don't arrive

What is the problem?

Thank you very much.


问:
foreach for mybatis returns Null results
My mapper xml is like this.

```<code><mapper namespace="EmployeeDaoMapper">
<resultMap id="employeeResultMap" type="Employee">
    <result property="employeeName" column="name"/>
    <result property="employeeId" column="employee_id"/>
</resultMap>

<select id="getEmployees" parameterType="list" resultMap="employeeResultMap">
<!--<select id="getEmployees" resultType="Employee">-->
    SELECT
    <foreach item="item" index="index" collection="list" separator="," >
        #{item}
    </foreach>
    FROM employees
    WHERE LOWER (name) LIKE LOWER(#{searchQuery} +'%') OR
    LOWER(login) LIKE LOWER(#{searchQuery} +'%') OR
    LOWER( employee_id ) LIKE LOWER(#{searchQuery} + '%')
    LIMIT #{resultsLimit}

</select>
</code>```

EmployeeMapper Interface

```<code>List<Employee> getEmployees(@Param("searchQuery") String searchQuery, @Param("resultsLimit") int
        resultsLimit, @Param("list") List<String> attributes);
</code>```

query returns list of null.

Instead of foreach, if i directly add column names then it works fine.

I am not sure what mistake i am making. I checked query, it is building query correctly, still unable to fetch results.

答: Try changing #{item} to ${item}.  With #{item} you are telling MyBatis that there should be a prepared statement parameter marker and that is invalid for a salect column list.  If you use ${item}, then MyBatis will write the string directly into the SQL.</p>

Body:
My mapper xml is like this.

<mapper namespace="EmployeeDaoMapper">
<resultMap id="employeeResultMap" type="Employee">
    <result property="employeeName" column="name"/>
    <result property="employeeId" column="employee_id"/>
</resultMap>

<select id="getEmployees" parameterType="list" resultMap="employeeResultMap">

    SELECT
    <foreach item="item" index="index" collection="list" separator="," >
        #{item}
    </foreach>
    FROM employees
    WHERE LOWER (name) LIKE LOWER(#{searchQuery} +'%') OR
    LOWER(login) LIKE LOWER(#{searchQuery} +'%') OR
    LOWER( employee_id ) LIKE LOWER(#{searchQuery} + '%')
    LIMIT #{resultsLimit}

</select>

EmployeeMapper Interface

List<Employee> getEmployees(@Param("searchQuery") String searchQuery, @Param("resultsLimit") int
        resultsLimit, @Param("list") List<String> attributes);

query returns list of null.

Instead of foreach, if i directly add column names then it works fine.

I am not sure what mistake i am making. I checked query, it is building query correctly, still unable to fetch results.


问:
objective-c Bridging header not found in swift compiler-code generation
I am doing an ios app  in swift 3. And I want to add ARKitwhich is available in objective-c. I dragged all objective-c files into my project then it asked to create bridging header. So I let it to create. And I imported all objective-c.h files inside that like this.

But when I try to build its showing 22 number of issues like UIViewcannot identify etc..

Then I tried to add the bridging headerpath to build settings under swift compiler - code generation. But I dont see objective-c Bridging headersection under that.

Please help me. What can I do to add these objective-c files into my swift 3 project successfully.
Thanks

答:
The Objective-C bridging header setting can be found under Swift Compiler - General under Build Settings.

But I like to add the bridging header by having Xcode generate it for me. I add a junk Objective-C class by File > New > File... and it will ask me if I want to add a bridging header to my project.

If you do that, you'll only need to move whatever you have in your bridging header now to that one and delete the header you have now. The header will be set properly in the project's settings.


问:
How to render contents in all components using react native?
I want to add header and footer in all pages like below.

Example :

Then how render header and footer in other components ?

That means write code once then how render it in various pages?

答: Using react-native-router-flux makes what you aim for pretty easy if I got your question right. Check out the documentation https://github.com/aksonov/react-native-router-flux </p>


问:
Round to Highest Factor with Variable Scale?
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number?  For example:

```<code>num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000
</code>```

答:
```<code>function num_to_scale($number) {
  $multiple=1; $test=1;
  for ($i=1; $test>=1; $i++) {
    $factor = $multiple/10;
    $test = $number/$multiple;
    $multiple = $multiple*10;
    $scale = floor($number/$factor)*$factor;
  } return $scale;
}
</code>```

or more simply:

```<code>function num_to_scale($n) {
  $m=1; $t=1;
  for ($i=1; $t>=1; $i++) {
    $f=$m/10; $t=$n/$m; $m=$m*10; $s=floor($n/$f)*$f;
  } return $s;
}
</code>```

Combined with a helper function to convert integers to text strings, we can easily do something like this:

```<code>echo 'Over '.num_to_scale(5395206).' units sold.';
// Over five million units sold.
</code>```

Body:
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number?  For example:

num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000

Body:
function num_to_scale($number) {
  $multiple=1; $test=1;
  for ($i=1; $test>=1; $i++) {
    $factor = $multiple/10;
    $test = $number/$multiple;
    $multiple = $multiple*10;
    $scale = floor($number/$factor)*$factor;
  } return $scale;
}

or more simply:

function num_to_scale($n) {
  $m=1; $t=1;
  for ($i=1; $t>=1; $i++) {
    $f=$m/10; $t=$n/$m; $m=$m*10; $s=floor($n/$f)*$f;
  } return $s;
}

Combined with a helper function to convert integers to text strings, we can easily do something like this:

echo 'Over '.num_to_scale(5395206).' units sold.';
// Over five million units sold.


问:
Best way to render model attribute key names in views?
I'm writing show and index views to render model objects and instead of hardcoding model attribute title names into the view I'd like to find a better way of rendering these titles and assigning them to their related variables for future rendering use.

Could you advise as to a best practice solution?

Old hardcoded:

```<code><tr>
  <td>Company name</td> # Would like to interpolate readable vers of attr key here.
  <td><%= @quote.co_name %></td>
</tr>
<tr>
  <td>Company number</td>
  <td><%= @quote.co_number %></td>
</tr>
<tr>
  <td>Office postcode</td>
  <td><%= @quote.postcode %></td>
</tr>
<tr>
  <td>Industry</td>
  <td><%= @quote.industry %></td>
</tr>
</code>```

答:
If you don't want to hardcode the column names but want them to be readable you can make use of ActiveRecord translations

en:
  activerecord:
    attributes:
      quote:
        co_name: "Company name"
        co_number: "Company number"
        postcode: "Office postcode"
        industry: "Industry"
```

<p>Use <strong><code>human_attribute_name</code></strong> to display the localized attribute name</p>

```

  <%= Quote.human_attribute_name(:co_name) %>
  <%= @quote.co_name %>

```

<p><strong>NOTE:</strong> Advantage of using this format is you will also get proper names in </p>

```@quote.errors.full_messages
#=> ["Company name can't be blank", "Company number can't be blank"]
```

Body:
I'm writing show and index views to render model objects and instead of hardcoding model attribute title names into the view I'd like to find a better way of rendering these titles and assigning them to their related variables for future rendering use.

Could you advise as to a best practice solution?

Old hardcoded:

  Company name	 # Would like to interpolate readable vers of attr key here.
  <%= @quote.co_name %>

  Company number
  <%= @quote.co_number %>

  Office postcode
  <%= @quote.postcode %>

  Industry
  <%= @quote.industry %>

Body:
If you don't want to hardcode the column names but want them to be readable you can make use of ActiveRecord translations

en:
  activerecord:
    attributes:
      quote:
        co_name: "Company name"
        co_number: "Company number"
        postcode: "Office postcode"
        industry: "Industry"

Use human_attribute_name to display the localized attribute name

<tr>
  <td><%= Quote.human_attribute_name(:co_name) %></td>
  <td><%= @quote.co_name %></td>
</tr>

NOTE: Advantage of using this format is you will also get proper names in

@quote.errors.full_messages
#=> ["Company name can't be blank", "Company number can't be blank"]


问:
Dynamically add a new filter
Is it possible to add a new filter in the filter chain dynamically? I mean by checking a condition/configuration can we include or exclude a specific filter from the filter chain?</p>

答: I believe simple solution for such requirement is to add filter with condition in doFilter method to filter chain. You will always have this filter in chain, but when condition is not satisfied filter will just pass control to the next filter.</p>

Title: Dynamically add a new filter


问:
XmlDocumentFragment set InnerXml fails with not declared prefix
I have an XML document which basically looks like this:

```<code><ArrayOfAspect xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Aspect i:type="TransactionAspect">
        ...
    </Aspect>
    <Aspect i:type="TransactionAspect">
        ...
    </Aspect>
</ArrayOfAspect>
</code>```

And I want to append a new Aspect to this list.

 In order to do so I load this xml from a file, create a XmlDocumentFragment and load the new Aspect from a file (which is basically a template I fill with data). Then I fill the document fragment with the new aspect and append it as a child.

But when I try to set the xml of this fragment it fails because the prefix i is not defined.

```<code>// Load all aspects
var aspectsXml = new XmlDocument();
aspectsXml.Load("aspects.xml");

// Create and fill the fragment
var fragment = aspectsXml.CreateDocumentFragment();
fragment.InnerXml = _templateIFilledWithData; // This fails because i is not defined

// Add the new child
aspectsXml.AppendChild(fragment)
</code>```

This is how the template looks like:

```<code><Aspect i:type="TransactionAspect">
    <Value>$VALUES_PLACEHOLDER$</Value>
    ...
</Aspect>
</code>```

Note that I don't want to create POCOs for this and serialize them since the aspects are actualy quite big and nested and I have the same problem with some other xml files as well.

EDIT:

jdweng proposed to use XmlLinq (Which is way better than what I used before, so thanks). Here is the code I try to use with XmlLinq (still failing because of undeclared prefix):

```<code>var aspects = XDocument.Load("aspects.xml");
var newAspects = EXlement.Parse(_templateIFilledWithData); // Fails here - Undeclared prefix 'i'
aspects.Root.add(newAspect);
</code>```

答:
Use xml linq :</p>

```<code>using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication57
{
    class Program
    {
        const string URL = "http://goalserve.com/samples/soccer_inplay.xml";
        static void Main(string[] args)
        {
            string xml =
                "<ArrayOfAspect xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                    "<Aspect i:type=\"TransactionAspect\">" +
                   "</Aspect>" +
                    "<Aspect i:type=\"TransactionAspect\">" +
                    "</Aspect>" +
                "</ArrayOfAspect>";

            XDocument doc = XDocument.Parse(xml);

            XElement root = doc.Root;
            XNamespace nsI = root.GetNamespaceOfPrefix("i");

            root.Add(new XElement("Aspect", new object[] {
                new XAttribute(nsI + "type", "TransactionAspect"),
                new XElement("Value", "$VALUES_PLACEHOLDER$")
            }));

        }

    }

}
</code>```

Body:
I have an XML document which basically looks like this:

<ArrayOfAspect xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Aspect i:type="TransactionAspect">
        ...
    </Aspect>
    <Aspect i:type="TransactionAspect">
        ...
    </Aspect>
</ArrayOfAspect>

And I want to append a new Aspect to this list.

 In order to do so I load this xml from a file, create a XmlDocumentFragment and load the new Aspect from a file (which is basically a template I fill with data). Then I fill the document fragment with the new aspect and append it as a child.

But when I try to set the xml of this fragment it fails because the prefix i is not defined.

// Load all aspects
var aspectsXml = new XmlDocument();
aspectsXml.Load("aspects.xml");

// Create and fill the fragment
var fragment = aspectsXml.CreateDocumentFragment();
fragment.InnerXml = _templateIFilledWithData; // This fails because i is not defined

// Add the new child
aspectsXml.AppendChild(fragment)

This is how the template looks like:

<Aspect i:type="TransactionAspect">
    <Value>$VALUES_PLACEHOLDER$</Value>
    ...
</Aspect>

Note that I don't want to create POCOs for this and serialize them since the aspects are actualy quite big and nested and I have the same problem with some other xml files as well.

EDIT:

jdweng proposed to use XmlLinq (Which is way better than what I used before, so thanks). Here is the code I try to use with XmlLinq (still failing because of undeclared prefix):

var aspects = XDocument.Load("aspects.xml");
var newAspects = EXlement.Parse(_templateIFilledWithData); // Fails here - Undeclared prefix 'i'
aspects.Root.add(newAspect);

Body:
Use xml linq :

using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication57
{
    class Program
    {
        const string URL = "http://goalserve.com/samples/soccer_inplay.xml";
        static void Main(string[] args)
        {
            string xml =
                "<ArrayOfAspect xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                    "<Aspect i:type=\"TransactionAspect\">" +
                   "</Aspect>" +
                    "<Aspect i:type=\"TransactionAspect\">" +
                    "</Aspect>" +
                "</ArrayOfAspect>";

            XDocument doc = XDocument.Parse(xml);

            XElement root = doc.Root;
            XNamespace nsI = root.GetNamespaceOfPrefix("i");

            root.Add(new XElement("Aspect", new object[] {
                new XAttribute(nsI + "type", "TransactionAspect"),
                new XElement("Value", "$VALUES_PLACEHOLDER$")
            }));

        }

    }

}


问:
Exception Handling SQL
I created a user defined function that calculates the quantity in stock for a product

```<code>CREATE OR REPLACE FUNCTION function_quantityInStock(
    oldProductQuantity IN INTEGER,
    orderedQuan IN INTEGER)
    RETURN INTEGER
IS
    v_newQuantity INTEGER;
    v_oldQuantity INTEGER;
    v_orderedQuan INTEGER;
BEGIN
    v_newquantity := oldProductQuantity - orderedQuan;
    RETURN v_newquantity;
EXCEPTION
    WHEN OTHERS THEN
        dbms_output.put_line('Please check your data.');
END function_quantityInstock;
</code>```

I then create a trigger that updates the table by calling the function

```<code>CREATE OR REPLACE TRIGGER TRIGGER_QUANTITY AFTER INSERT ON ordered_product
FOR EACH ROW
DECLARE
    v_oldQuantity INTEGER;
BEGIN
    SELECT PRODUCT_QUANTITYINSTOCK INTO v_oldQuantity
    FROM   product
    WHERE  product_id = :NEW.product_id;

    UPDATE PRODUCT
    SET    product_quantityinstock =
             function_quantityINSTOCK(v_oldQuantity, :NEW.ORDERED_PRODUCTQUANTITY)
    WHERE product_id = :NEW.product_id;
END;
</code>```

I want to display a message when the user enters invalid data but my exception block doesnt do that.

I use the following anonyomus block to test the function:

```<code>SET SERVEROUTPUT ON;

DECLARE
    v_productID    ordered_product.product_id%TYPE:= &ProductID;
    v_orderID      ordered_product.order_id%TYPE:=&OrderID;
    v_orderedQuan  ordered_product.ordered_productQuantity%TYPE := &OrderedProductQuantity;
    v_totalCost    ordered_product.ordered_productTotalCost%TYPE := '&TotalCost';
BEGIN
    INSERT INTO ordered_product VALUES
    (v_orderID, v_productID, v_orderedQuan, v_totalCost);

    dbms_output.put_line('A new record has been inserted.');
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        dbms_output.put_line('Invalid data!');
    WHEN VALUE_ERROR THEN
        dbms_output.put_line('Error! Please check your values.'|| SQLERRM);
END;
</code>```

答:
You might be missing exec dbms_output.enable(10000) and therefore not be seeing the output.

You should throw the exception using

```<code>raise_application_error(-20000, 'Please check your data.');
</code>```

Also it's bad practice to catch all exceptions using when others and then ignore them.

Title: Exception Handling SQL

Body:
I created a user defined function that calculates the quantity in stock for a product

CREATE OR REPLACE FUNCTION function_quantityInStock(
    oldProductQuantity IN INTEGER,
    orderedQuan IN INTEGER)
    RETURN INTEGER
IS
    v_newQuantity INTEGER;
    v_oldQuantity INTEGER;
    v_orderedQuan INTEGER;
BEGIN
    v_newquantity := oldProductQuantity - orderedQuan;
    RETURN v_newquantity;
EXCEPTION
    WHEN OTHERS THEN
        dbms_output.put_line('Please check your data.');
END function_quantityInstock;

I then create a trigger that updates the table by calling the function

CREATE OR REPLACE TRIGGER TRIGGER_QUANTITY AFTER INSERT ON ordered_product
FOR EACH ROW
DECLARE
    v_oldQuantity INTEGER;
BEGIN
    SELECT PRODUCT_QUANTITYINSTOCK INTO v_oldQuantity
    FROM   product
    WHERE  product_id = :NEW.product_id;

    UPDATE PRODUCT
    SET    product_quantityinstock =
             function_quantityINSTOCK(v_oldQuantity, :NEW.ORDERED_PRODUCTQUANTITY)
    WHERE product_id = :NEW.product_id;
END;

I want to display a message when the user enters invalid data but my exception block doesnt do that.

I use the following anonyomus block to test the function:

SET SERVEROUTPUT ON;

DECLARE
    v_productID    ordered_product.product_id%TYPE:= &ProductID;
    v_orderID      ordered_product.order_id%TYPE:=&OrderID;
    v_orderedQuan  ordered_product.ordered_productQuantity%TYPE := &OrderedProductQuantity;
    v_totalCost    ordered_product.ordered_productTotalCost%TYPE := '&TotalCost';
BEGIN
    INSERT INTO ordered_product VALUES
    (v_orderID, v_productID, v_orderedQuan, v_totalCost);

    dbms_output.put_line('A new record has been inserted.');
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        dbms_output.put_line('Invalid data!');
    WHEN VALUE_ERROR THEN
        dbms_output.put_line('Error! Please check your values.'|| SQLERRM);
END;

Body:
You might be missing exec dbms_output.enable(10000) and therefore not be seeing the output.

You should throw the exception using

raise_application_error(-20000, 'Please check your data.');

Also it's bad practice to catch all exceptions using when others and then ignore them.


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
I don't think it's the most readable way of doing it.  Chained if-else if looks much better.  But if you want to stick with it and don't want to be so close to an infinite loop, you could do something like this:

```<code>do
{
    if (...)
        break;
    ...
} while (false);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
I don't think it's the most readable way of doing it.  Chained if-else if looks much better.  But if you want to stick with it and don't want to be so close to an infinite loop, you could do something like this:

do
{
    if (...)
        break;
    ...
} while (false);


问:
Querying XML file in SQL Server
This is my xml file

```<code><Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Parents>
    <Parent id="1234">
      <name>
        <firstname>ABC</firstname>
        <lastname>XYSX</lastname>
      </name>
    </Parent>
    <Parent id="1235">
      <name>
        <firstname>TFU</firstname>
        <lastname>GHY</lastname>
      </name>
    </Parent>
  </Parents>
  <Children>
    <Child id="457" Parentid="1234">
      <name>
        <cfirstname>JOHN</cfirstname>
        <clastname>SMITH</clastname>
      </name>
    </Child>
    <Child id="459" Parentid="1235">
      <name>
        <cfirstname>DAVID</cfirstname>
        <clastname>SMITH</clastname>
      </name>
    </Child>
  </Children>
</Detials>
</code>```

I stored it in a table (using Bulk Insert).

When I query like this

```<code>SELECT
    x.c.value('(./Parents/Parent/@id)[1]', 'nvarchar(4)' ) AS id
FROM
    T1 s
CROSS APPLY
    s.XMLData.nodes('Detials') AS x(c)
</code>```

I get the result as

```<code>Id
----
1234
</code>```

When I changed it a little bit

```<code>SELECT
    x.c.value('@id', 'nvarchar(4)' ) AS id
FROM
    T1 s
CROSS APPLY
    s.XMLData.nodes('/Detials/Parents/Parent') AS x(c)
</code>```

I get:

```<code>Id
----
1234
1235
</code>```

I just want to query them to result like this

```<code>Parent_id | firstname | lastname | Child_id | Child_First_name | child_last_name
----------+-----------+----------+----------+------------------+-----------
1234      | ABC       | XYSX     |    457   |      JOHN        | SMITH
1235      | TFU       | GHY      |    459   |      DAVID       | SMITH
</code>```

How could I do this in query ?

In my result I want total no. of rows which depends on the Parentid. If my xml file contains 6 <parent id> then my query should show all 6 rows for each parent id's along with comparing the Childid's to also be included if the Parentid matches in <child> tag.

Thanks, Jayendran

答:
You were on the right track, but this would require a left join on the two result sets Parent/Children

Example

```<code>Declare @T1 table (ID int,XMLData xml)
Insert Into @T1 values
(1,'<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Parents><Parent id="1234"><name><firstname>ABC</firstname><lastname>XYSX</lastname></name></Parent><Parent id="1235"><name><firstname>TFU</firstname><lastname>GHY</lastname></name></Parent></Parents><Children><Child id="457" Parentid="1234"><name><cfirstname>JOHN</cfirstname><clastname>SMITH</clastname></name></Child><Child id="459" Parentid="1235"><name><cfirstname>DAVID</cfirstname><clastname>SMITH</clastname></name></Child></Children></Detials>')

Select A.ID
      ,B.*
 From  @T1 A
 Cross Apply (
                Select B1.Parent_id
                      ,B1.First_Name
                      ,B1.Last_Name
                      ,B2.Child_id
                      ,B2.Child_First_name
                      ,B2.child_last_name
                 From  (
                        Select
                            Parent_id  = x.c.value('@id', 'nvarchar(4)' )
                           ,First_Name = x.c.value('(name/firstname)[1]','varchar(50)')
                           ,Last_Name  = x.c.value('(name/lastname)[1]','varchar(50)')
                        From @T1 s
                        Cross Apply s.XMLData.nodes('/Detials/Parents/Parent') AS x(c)
                       ) B1
                 Left Join  (
                        Select
                            pt_id      = x.c.value('@Parentid', 'nvarchar(4)' )
                           ,Child_id   = x.c.value('@id', 'nvarchar(4)' )
                           ,Child_First_name  = x.c.value('(name/cfirstname)[1]','varchar(50)')
                           ,child_last_name   = x.c.value('(name/clastname)[1]','varchar(50)')
                        From @T1 s
                        Cross Apply s.XMLData.nodes('/Detials/Children/Child ') AS x(c)
                       ) B2
                   on  B1.Parent_id = B2.pt_id
             ) B
</code>```

Returns

Title: Querying XML file in SQL Server

Body:
This is my xml file

<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Parents>
    <Parent id="1234">
      <name>
        <firstname>ABC</firstname>
        <lastname>XYSX</lastname>
      </name>
    </Parent>
    <Parent id="1235">
      <name>
        <firstname>TFU</firstname>
        <lastname>GHY</lastname>
      </name>
    </Parent>
  </Parents>
  <Children>
    <Child id="457" Parentid="1234">
      <name>
        <cfirstname>JOHN</cfirstname>
        <clastname>SMITH</clastname>
      </name>
    </Child>
    <Child id="459" Parentid="1235">
      <name>
        <cfirstname>DAVID</cfirstname>
        <clastname>SMITH</clastname>
      </name>
    </Child>
  </Children>
</Detials>

I stored it in a table (using Bulk Insert).

When I query like this

SELECT
    x.c.value('(./Parents/Parent/@id)[1]', 'nvarchar(4)' ) AS id
FROM
    T1 s
CROSS APPLY
    s.XMLData.nodes('Detials') AS x(c)

I get the result as

Id
----
1234

When I changed it a little bit

SELECT
    x.c.value('@id', 'nvarchar(4)' ) AS id
FROM
    T1 s
CROSS APPLY
    s.XMLData.nodes('/Detials/Parents/Parent') AS x(c)

I get:

Id
----
1234
1235

I just want to query them to result like this

Parent_id | firstname | lastname | Child_id | Child_First_name | child_last_name
----------+-----------+----------+----------+------------------+-----------
1234      | ABC       | XYSX     |    457   |      JOHN        | SMITH
1235      | TFU       | GHY      |    459   |      DAVID       | SMITH

How could I do this in query ?

In my result I want total no. of rows which depends on the Parentid. If my xml file contains 6 <parent id> then my query should show all 6 rows for each parent id's along with comparing the Childid's to also be included if the Parentid matches in <child> tag.

Thanks, Jayendran

Body:
You were on the right track, but this would require a left join on the two result sets Parent/Children

Example

Declare @T1 table (ID int,XMLData xml)
Insert Into @T1 values
(1,'<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Parents><Parent id="1234"><name><firstname>ABC</firstname><lastname>XYSX</lastname></name></Parent><Parent id="1235"><name><firstname>TFU</firstname><lastname>GHY</lastname></name></Parent></Parents><Children><Child id="457" Parentid="1234"><name><cfirstname>JOHN</cfirstname><clastname>SMITH</clastname></name></Child><Child id="459" Parentid="1235"><name><cfirstname>DAVID</cfirstname><clastname>SMITH</clastname></name></Child></Children></Detials>')

Select A.ID
      ,B.*
 From  @T1 A
 Cross Apply (
                Select B1.Parent_id
                      ,B1.First_Name
                      ,B1.Last_Name
                      ,B2.Child_id
                      ,B2.Child_First_name
                      ,B2.child_last_name
                 From  (
                        Select
                            Parent_id  = x.c.value('@id', 'nvarchar(4)' )
                           ,First_Name = x.c.value('(name/firstname)[1]','varchar(50)')
                           ,Last_Name  = x.c.value('(name/lastname)[1]','varchar(50)')
                        From @T1 s
                        Cross Apply s.XMLData.nodes('/Detials/Parents/Parent') AS x(c)
                       ) B1
                 Left Join  (
                        Select
                            pt_id      = x.c.value('@Parentid', 'nvarchar(4)' )
                           ,Child_id   = x.c.value('@id', 'nvarchar(4)' )
                           ,Child_First_name  = x.c.value('(name/cfirstname)[1]','varchar(50)')
                           ,child_last_name   = x.c.value('(name/clastname)[1]','varchar(50)')
                        From @T1 s
                        Cross Apply s.XMLData.nodes('/Detials/Children/Child ') AS x(c)
                       ) B2
                   on  B1.Parent_id = B2.pt_id
             ) B

Returns


问:
Assign first page in Oracle APEX 5 based on login
I'm currently building a recruiting application to replace one currently in use.

I want to be able to set the first page a user sees based on login. I'm currently using Application Express Authentication, but I also have a logins table that contains office, user name and user type, so when the user name in :APP_USER. matches the user name in the login table, it will pull the user type.

So if a recruiter logs in I want them to go to page 1, which is a recruiting dashboard, but if a salesmen logs in I want them to go to page 20, which is a sales dashboard.

How can I accomplish this?

Thanks in advance!

答:
For anyone else that is looking to accomplish this, Tom had the perfect solution, here's how you put it into you custom authentication scheme.

When you edit the scheme, in the PL/SQL Code box enter your code so it looks like this

```<code>PROCEDURE post_authentication IS
BEGIN
DECLARE
  l_type logins.login_type%TYPE;
  l_url VARCHAR2(4000);
BEGIN
  SELECT login_type
    INTO l_type
    FROM logins
   WHERE upper(:P101_USERNAME) = USERNAME;

  l_url :=
  CASE l_type
  WHEN 'Sales' THEN
    'f?p=' || V('APP_ALIAS') || ':SALES_DASH:' || V('APP_SESSION')
  WHEN 'Recruiter' THEN
    'f?p=' || V('APP_ALIAS') || ':RECRUITER_DASH:' || V('APP_SESSION')
  WHEN 'Regional' THEN
    'f?p=' || V('APP_ALIAS') || ':REGIONAL_DASH:' || V('APP_SESSION')
  WHEN 'Admin' THEN
    'f?p=' || V('APP_ALIAS') || ':ADMIN_DASH:' || V('APP_SESSION')
  WHEN 'National' THEN
    'f?p=' || V('APP_ALIAS') || ':NATIONAL_DASH:' || V('APP_SESSION')
  ELSE  -- go to home page
    'f?p=' || V('APP_ALIAS') || ':HOME:' || V('APP_SESSION')
  END;

  APEX_UTIL.SET_SESSION_STATE('FSP_AFTER_LOGIN_URL', l_url);
END;
END post_authentication;
</code>```

Then below in the in the Post-Authentication Procedure Name field under Login Processing make sure you put post-Authentication or what ever you decided to name the procedure on the PL/SQL box.

This will allow you redirect users based on user type if you're using a custom login table.

Body:
For anyone else that is looking to accomplish this, Tom had the perfect solution, here's how you put it into you custom authentication scheme.

When you edit the scheme, in the PL/SQL Code box enter your code so it looks like this

PROCEDURE post_authentication IS
BEGIN
DECLARE
  l_type logins.login_type%TYPE;
  l_url VARCHAR2(4000);
BEGIN
  SELECT login_type
    INTO l_type
    FROM logins
   WHERE upper(:P101_USERNAME) = USERNAME;

  l_url :=
  CASE l_type
  WHEN 'Sales' THEN
    'f?p=' || V('APP_ALIAS') || ':SALES_DASH:' || V('APP_SESSION')
  WHEN 'Recruiter' THEN
    'f?p=' || V('APP_ALIAS') || ':RECRUITER_DASH:' || V('APP_SESSION')
  WHEN 'Regional' THEN
    'f?p=' || V('APP_ALIAS') || ':REGIONAL_DASH:' || V('APP_SESSION')
  WHEN 'Admin' THEN
    'f?p=' || V('APP_ALIAS') || ':ADMIN_DASH:' || V('APP_SESSION')
  WHEN 'National' THEN
    'f?p=' || V('APP_ALIAS') || ':NATIONAL_DASH:' || V('APP_SESSION')
  ELSE  -- go to home page
    'f?p=' || V('APP_ALIAS') || ':HOME:' || V('APP_SESSION')
  END;

  APEX_UTIL.SET_SESSION_STATE('FSP_AFTER_LOGIN_URL', l_url);
END;
END post_authentication;

Then below in the in the Post-Authentication Procedure Name field under Login Processing make sure you put post-Authentication or what ever you decided to name the procedure on the PL/SQL box.

This will allow you redirect users based on user type if you're using a custom login table.


问:
cannot set UILabel padding in tableViewcell
I have set my UILabel padding using StackOverflow's popular thread for resolving auto-layout issue.
This thread is basically a UILabel extension.

Part of the answer is:

```<code>class NRLabel : UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}
</code>```

Everything is working fine, padding has been added but i need to reload the tableViewcell to see the effect.

I have  overridden my customCell's viewWillLayoutSubviews() function like this for padding

```<code> self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
</code>```

And the effect is like this.

You see, first label is getting it's padding after reloading the cell.

Pls suggest how to  achieve UILabel padding by using the extension mentioned above so that this issue is resolved.

答:
You have nothing in NRLabel which tells it to redraw when the textInsets property is changed.  You need to do something like this:

```<code>var textInsets = UIEdgeInsets.zero {
    didSet {
        invalidateIntrinsicContentSize()
        setNeedsDisplay()
    }
}
</code>```

So now when the textInsets property is changed the NRLabel will be re-drawn with the new text insets.

Body:
I have set my UILabel padding using StackOverflow's popular thread for resolving auto-layout issue.
This thread is basically a UILabel extension.

Part of the answer is:

class NRLabel : UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}

Everything is working fine, padding has been added but i need to reload the tableViewcell to see the effect.

I have  overridden my customCell's viewWillLayoutSubviews() function like this for padding

 self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)

And the effect is like this.

You see, first label is getting it's padding after reloading the cell.

Pls suggest how to  achieve UILabel padding by using the extension mentioned above so that this issue is resolved.

Body:
You have nothing in NRLabel which tells it to redraw when the textInsets property is changed.  You need to do something like this:

var textInsets = UIEdgeInsets.zero {
    didSet {
        invalidateIntrinsicContentSize()
        setNeedsDisplay()
    }
}

So now when the textInsets property is changed the NRLabel will be re-drawn with the new text insets.


问:
How to call a user defined function with NULL values for one of its input parameter?
My UDF's body has the following HAVING class.

```<code>HAVING
         Company.Description            = @Company       AND
         SystemCustomerType.Description = @CustomerType
</code>```

I tried to call this by this following syntax.

```<code>SELECT * FROM FunctionName('ABC_Company',NULL)
</code>```

And also tried to set default value as NULL for @CustomerType parameter. And called the function by

```<code>SELECT * FROM FunctionName('ABC_Company',default)
</code>```

答:
Try this:

```<code>where (Company.Description = @Company or @Company is null)
and (SystemCustomerType.Description = @CustomerType or @CustomerType is null)
</code>```

Then use:

```<code>select * from FunctionName('ABC_Company',NULL)
</code>```

Body:
My UDF's body has the following HAVING class.

HAVING
         Company.Description            = @Company       AND
         SystemCustomerType.Description = @CustomerType

I tried to call this by this following syntax.

SELECT * FROM FunctionName('ABC_Company',NULL)

And also tried to set default value as NULL for @CustomerType parameter. And called the function by

SELECT * FROM FunctionName('ABC_Company',default)

Body:
Try this:

where (Company.Description = @Company or @Company is null)
and (SystemCustomerType.Description = @CustomerType or @CustomerType is null)

Then use:

select * from FunctionName('ABC_Company',NULL)


问:
AngularJS: Table with ng-repeat on table row / column
I need to create a table from an array of objects but I don't want to hardcode the table. I can't do this or this for example. I rather need nested ng-repeats like this. But my case is a little bit different because I have columns which contain two values in an array. The data looks like this:

```<code>[
   {
      "foo":"bar",...,
      "key1":[
         "value1",
         "value2"
      ],
      "key2":[
         "value1",
         "value2"
      ],...,
      "more_foo":"more_bar"
   },...
]
</code>```

I want the values (which are always strings) of all objects (which have always an equal structure) from the array in the table rows where each key should be the column name. Like this:

table,
th,
td {
  border: 1px solid black;
  text-align: center;
  border-spacing: 0;
}

td,
th {
  padding: 0.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th>foo</th>
      <th colspan="2">key1</th>
      <th colspan="2">key2</th>
      <th>more_foo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>bar</td>
      <td>value1</td>
      <td>value2</td>
      <td>value1</td>
      <td>value2</td>
      <td>more_bar</td>
    </tr>
  </tbody>
</table></code>```

Here is what I have come up with:

```<code><table>
    <thead>
    <tr>
        <th ng-repeat="(propName, prop) in myArray[0]"
            colspan="{{isUpdateable(propName) ? 2 : undefined}}"> {{propName}}
        </th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="object in myArray | filter: searchFilter">
        <td ng-repeat="(propName, prop) in object" double-col>{{prop}}</td>
    </tr>
    </tbody>
</table>
</code>```

isUpdatable(propName) will return true if this value is an array and false if it is not. This will make it possible to have two tds in this column.

The double-col directive:

```<code>app.directive('double-col', function () {
    return {
        transclude: true,
        template: "<td>{{prop[0]}}</td><td class=\"changedProp\">{{prop[1]}}</td>"
    };
});
</code>```

I want this directive to replace the existing td with two tds if and only if prop is an array and otherwise do nothing to display prop (see td above).

Because you are on https://stackoverflow.com (the place where people post things that dont't work well yet), you can probably guess that my current code doesn't not work really well. I am also new to angularJS and have basically no understanding of custom directives (and probably most other stuff too) so it would be nice if someone could help me with this problem and provide an explanation as well.

答:
What about

```<code><tr ng-repeat="object in myArray | filter: searchFilter">
        <td ng-repeat="(propName, prop) in object" colspan="{{isArray(prop) ? prop.length : 1}}">
       <span ng-if="!isArray(prop)"> {{prop}}</span>
        <table ng-if="isArray(prop)"><tr>
    <td ng-repeat="prop1 in prop">
        {{prop1}}
    </td>
   </tr></table>
        </td>

    </tr>

$scope.isArray=function(prop){
return Array.isArray(prop);
}
</code>```

Here is working fiddle

Body:
I need to create a table from an array of objects but I don't want to hardcode the table. I can't do this or this for example. I rather need nested ng-repeats like this. But my case is a little bit different because I have columns which contain two values in an array. The data looks like this:

[
   {
      "foo":"bar",...,
      "key1":[
         "value1",
         "value2"
      ],
      "key2":[
         "value1",
         "value2"
      ],...,
      "more_foo":"more_bar"
   },...
]

I want the values (which are always strings) of all objects (which have always an equal structure) from the array in the table rows where each key should be the column name. Like this:

table,
th,
td {
  border: 1px solid black;
  text-align: center;
  border-spacing: 0;
}

td,
th {
  padding: 0.5em;
}

      foo
      key1
      key2
      more_foo

      bar
      value1
      value2
      value1
      value2
      more_bar

Here is what I have come up with:

         {{propName}}

        {{prop}}

isUpdatable(propName) will return true if this value is an array and false if it is not. This will make it possible to have two tds in this column.

The double-col directive:

app.directive('double-col', function () {
    return {
        transclude: true,
        template: "{{prop[0]}}	{{prop[1]}}	"
    };
});

I want this directive to replace the existing td with two tds if and only if prop is an array and otherwise do nothing to display prop (see td above).

Because you are on https://stackoverflow.com (the place where people post things that dont't work well yet), you can probably guess that my current code doesn't not work really well. I am also new to angularJS and have basically no understanding of custom directives (and probably most other stuff too) so it would be nice if someone could help me with this problem and provide an explanation as well.

Body:
What about

<tr ng-repeat="object in myArray | filter: searchFilter">
        <td ng-repeat="(propName, prop) in object" colspan="{{isArray(prop) ? prop.length : 1}}">
       <span ng-if="!isArray(prop)"> {{prop}}</span>
        <table ng-if="isArray(prop)"><tr>
    <td ng-repeat="prop1 in prop">
        {{prop1}}
    </td>
   </tr></table>
        </td>

    </tr>

$scope.isArray=function(prop){
return Array.isArray(prop);
}

Here is working fiddle


问:
How to start a python file while Windows starts?
I have a python file and I am running the file.

If Windows is shutdown and booted up again, how I can run that file every time Windows starts?

答:
Depending on what the script is doing, you may:

package it into a service, that should then be installed

add it to the windows registry (HKCU\Software\Microsoft\Windows\CurrentVersion\Run)

add a shortcut to it to the startup folder of start menu - its location may change with OS version, but installers always have some instruction to put a shortcut into that folder

use windows' task scheduler, and then you can set the task on several kind of events, including logon and on startup.

The actual solution depends on your needs, and what the script is actually doing.

Some notes on the differences:

Solution #1 starts the script with the computer, while solution #2 and #3 start it when the user who installed it logs in.

It is also worth to note that #1 always start the script, while #2 and #3 will start the script only on a specific user (I think that if you use the default user then it will start on everyone, but I am not sure of the details).

Solution #2 is a bit more "hidden" to the user, while solution #3 leaves much more control to the user in terms of disabling the automatic start.

Finally, solution #1 requires administrative rights, while the other two may be done by any user.

Solution #4 is something I discovered lately, and is very straightforward. The only problem I have noticed is that the python script will cause a small command window to appear.

As you can see, it all boils down to what you want to do; for instance, if it is something for your purposes only, I would simply drag it into startup folder.

In any case, lately I am leaning on solution #4, as the quickest and most straightforward approach.


问:
Bluemix user-created container - 'This page can’t be displayed'
Problem:  'This page can’t be displayed' when I select a user-defined container from Bluemix catalog.
 https://console.ng.bluemix.net/catalog/?category=containers&taxonomyNavigation=containers&env_id=ibm:yp:us-south

Background: The build successfully completed and the image was created

```<code>cf ic build -t tomcat-mine .
cf ic images |grep tomcat-mine
registry.ng.bluemix.net/ztechsec/tomcat-mine latest 7cd1e6870ffd 55 minutes ago      142 MB
</code>```

The container that was created in the previous step shows up under Bluemix Catalog > Containers.

When selecting the container that was created (tomcat-mine), the URL generates the 'This page can’t be displayed.' This URL generates the 'This page can’t be displayed' from the Bluemix -> Catalog > Containers:

https://catalog/images/tomcat-mine?org=28bfa082-2a8e-43cf-963d-7b7b28455603&space=085c044d-55cf-497a-8219-d6b668d63668&org_region=us-south&is_org_manager=false&ims_account=1177915&env_id=ibm:yp:us-south

Questions:

What would cause this issue?

What are possible workarounds?

答:
Are you able to inspect the image with the CLI?

cf ic inspect 7cd1e6870ffd - does that work for you?

Body:
Problem:  'This page can’t be displayed' when I select a user-defined container from Bluemix catalog.
 https://console.ng.bluemix.net/catalog/?category=containers&taxonomyNavigation=containers&env_id=ibm:yp:us-south

Background: The build successfully completed and the image was created

cf ic build -t tomcat-mine .
cf ic images |grep tomcat-mine
registry.ng.bluemix.net/ztechsec/tomcat-mine latest 7cd1e6870ffd 55 minutes ago      142 MB

The container that was created in the previous step shows up under Bluemix Catalog > Containers.

When selecting the container that was created (tomcat-mine), the URL generates the 'This page can’t be displayed.' This URL generates the 'This page can’t be displayed' from the Bluemix -> Catalog > Containers:

https://catalog/images/tomcat-mine?org=28bfa082-2a8e-43cf-963d-7b7b28455603&space=085c044d-55cf-497a-8219-d6b668d63668&org_region=us-south&is_org_manager=false&ims_account=1177915&env_id=ibm:yp:us-south

Questions:

What would cause this issue?

What are possible workarounds?


问:
How to make plotly axes display only integer numbers
I have a plotly barplot in a shiny app, showing factor levels on X axis. But on some number of inputs (2,3,4) it shows marks like 1.5, 2.5 etc (see an image). So there is a question: can I somehow make the X axis marks show only integer values?

答:
plotly is guessing your axis types since your cluster labels are numeric.  You can fix this by coercing your x var to a factor before/when plotting.

```<code>library(plotly)
library(dplyr)
mtcars_by_gear <- count(mtcars,gear)

plot_ly(mtcars_by_gear,
        x=~as.factor(gear),
        y=~n)
</code>```

If you want further control over axis labels you can use the layout() function's tick arguments, but the factor option seems better for your case.

```<code>plot_ly(mtcars_by_gear,
        x=~gear,
        y=~n,
        type="bar") %>%
  layout(xaxis=list(tickvals=~gear,ticktext=~gear))
</code>```

Body:
plotly is guessing your axis types since your cluster labels are numeric.  You can fix this by coercing your x var to a factor before/when plotting.

library(plotly)
library(dplyr)
mtcars_by_gear <- count(mtcars,gear)

plot_ly(mtcars_by_gear,
        x=~as.factor(gear),
        y=~n)

If you want further control over axis labels you can use the layout() function's tick arguments, but the factor option seems better for your case.

plot_ly(mtcars_by_gear,
        x=~gear,
        y=~n,
        type="bar") %>%
  layout(xaxis=list(tickvals=~gear,ticktext=~gear))


问:
unable to get JSON data from Restlet Client using Node Js
(I am totally new to Restlet client and Server scripting)

I am trying to get JSON Data from response body of the Restlet client using below code but I could not get that

```<code>var http = require('http');
var options = {
  host: 'staging.api.pearson.com',
  port: 80,
  path: '/sc-api/apis/content/urn:pearson:manifestation:db7eac5b-8f65-49dc-97bc-d0f5e824f135'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  res.on("data", function(chunk) {
    console.log("BODY: " + chunk);
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});
</code>```

Getting the below output:

But when using the Restlet client GUI, can able download the response BODY Json

Adding Environments details:

Browser Snapshot:

Kindly anybody suggest any way to do

(I am totally new to Restlet client and Server scripting)

Thanks

答: The only difference I see between your code and rest client GUI is the port. Is the host name a VIP? In that case, you shouldn't use port in your code.  Also as others said, use https as you are using It in GUI.

Body:
(I am totally new to Restlet client and Server scripting)

I am trying to get JSON Data from response body of the Restlet client using below code but I could not get that

var http = require('http');
var options = {
  host: 'staging.api.pearson.com',
  port: 80,
  path: '/sc-api/apis/content/urn:pearson:manifestation:db7eac5b-8f65-49dc-97bc-d0f5e824f135'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  res.on("data", function(chunk) {
    console.log("BODY: " + chunk);
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

Getting the below output:

But when using the Restlet client GUI, can able download the response BODY Json

Adding Environments details:

Browser Snapshot:

Kindly anybody suggest any way to do

(I am totally new to Restlet client and Server scripting)

Thanks


问:
Does this interface require a Null modem cable?
I am enclosing here the drawing of the RS-232 9 pin connection cable to link a XT2000i Blood analyser to a host PC. Is this just any serial port cable or a Null modem cable ?

Thanks. Chak.

Since @JTON said in the answer that other pins are not swapped, i am enclosing image of which pins are in use.

答: Since the lines is crossed it is a null-modem cable.</p>


问:
How To Pass Parameter in javascript find function?
Hie,

I have a json object which have a id field:

```<code>document = {
             id: 'some value',
             ...
           }
</code>```

And a list to store this documents.

```<code>var list = [{document}, {document} ...]
</code>```

Now I am trying to call javascript find() function on the list to return the document with a specific id as

```<code>list.find( document, id) => {
   if (document.id == id)
   return id
}
</code>```

But its not working. I checked and found that the id parameter value is not what I am passing but the index value of the document in the list. I tried changing the name hoping it was a error with keyword but the sae result.

So, How do I pass a custom parameter to the find function?

答:
It's a call back method that allows you to reference to variables outside of the scope of the callback.

Example:

```<code>var id = 10;
var foundDoc = list.find((document) => document.id == id);

// alternative syntax
var foundDoc = list.find((document) => {
  return document.id == id;
});
</code>```

In your example find takes a predicate that should return true/false if there is a match. On the first occurance of true (a match) that item is returned to the caller.

Body:
Hie,

I have a json object which have a id field:

document = {
             id: 'some value',
             ...
           }

And a list to store this documents.

var list = [{document}, {document} ...]

Now I am trying to call javascript find() function on the list to return the document with a specific id as

list.find( document, id) => {
   if (document.id == id)
   return id
}

But its not working. I checked and found that the id parameter value is not what I am passing but the index value of the document in the list. I tried changing the name hoping it was a error with keyword but the sae result.

So, How do I pass a custom parameter to the find function?

Body:
It's a call back method that allows you to reference to variables outside of the scope of the callback.

Example:

var id = 10;
var foundDoc = list.find((document) => document.id == id);

// alternative syntax
var foundDoc = list.find((document) => {
  return document.id == id;
});

In your example find takes a predicate that should return true/false if there is a match. On the first occurance of true (a match) that item is returned to the caller.


问:
left and right alignment rows inside Listview
I want to implement interface like iphone sms:

Now I have chat listview with my custom ChatAdapter, incoming and outcoming messages inflates from different layouts:

outcoming layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"
    android:background="@drawable/question_bubble"
    android:paddingBottom="10dp"
    android:paddingLeft="20dp"
    android:paddingRight="27dp"
    android:paddingTop="10dp"
    android:textColor="@color/BlackColor"
    android:textSize="18sp" />
</code>```

incoming layout:

```<code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:autoLink="all"
    android:background="@drawable/answer_bubble"
    android:paddingLeft="27dp"
    android:paddingRight="20dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:textColor="@color/BlackColor"
    android:textSize="18sp"/>
</code>```

I use "layout_gravity", but it doesnt work inside list view. Result:

How can I align question messages to right side?

答:
if you encounter such problem make sure that your text layout is set in this format

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/bubble_layout_parent"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/bubble_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/chat_bubble_right">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:maxEms="12"
        android:text="Hi! new message"
        android:textColor="@color/colorWhite"
        android:textSize="15sp" />
</LinearLayout>
</code>```

notice that the parent LinearLayout width is set to match_parent while others are set to wrap_content.
this kept me up for hours.

Body:
I want to implement interface like iphone sms:

Now I have chat listview with my custom ChatAdapter, incoming and outcoming messages inflates from different layouts:

outcoming layout:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right"
    android:background="@drawable/question_bubble"
    android:paddingBottom="10dp"
    android:paddingLeft="20dp"
    android:paddingRight="27dp"
    android:paddingTop="10dp"
    android:textColor="@color/BlackColor"
    android:textSize="18sp" />

incoming layout:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:autoLink="all"
    android:background="@drawable/answer_bubble"
    android:paddingLeft="27dp"
    android:paddingRight="20dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:textColor="@color/BlackColor"
    android:textSize="18sp"/>

I use "layout_gravity", but it doesnt work inside list view. Result:

How can I align question messages to right side?

Body:
if you encounter such problem make sure that your text layout is set in this format

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/bubble_layout_parent"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:id="@+id/bubble_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/chat_bubble_right">

    <TextView
        android:id="@+id/message_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:maxEms="12"
        android:text="Hi! new message"
        android:textColor="@color/colorWhite"
        android:textSize="15sp" />
</LinearLayout>

notice that the parent LinearLayout width is set to match_parent while others are set to wrap_content.
this kept me up for hours.


问:
How to update a docker swarm service with no replication with zero downtime?
I want to update docker swarm service without down-time. The problem is that I don't have enough resources to have service replication. Is there anyway to do this?</p>

答:
The default with swarm mode is to stop containers before starting new ones. There is a pull request (#30261) that was added in 17.05 to optionally start a new instance before stopping the old one. The syntax for this is:

```<code>docker service update --update-order start-first ...
</code>```

This has not been added to updating stacks yet, you can track that request on issue #32586.

Body:
The default with swarm mode is to stop containers before starting new ones. There is a pull request (#30261) that was added in 17.05 to optionally start a new instance before stopping the old one. The syntax for this is:

docker service update --update-order start-first ...

This has not been added to updating stacks yet, you can track that request on issue #32586.


问:
Why does my array not have the right length after initializing it?
I want to initialize an array of variable length with random zeros and ones. My problem is that the array I created seems to only have a length of 4 elements.
Why is that?</p>

```<code>int main()
{
    int i, j;
    int length = 20;
    int *array = (int *) calloc(length, sizeof(int));
    for (i = 1; i < length; i++) {
        array[i] = 1;
        printf("%d", array[i]);
    }
    printf("\n");
    for (j = 0; j < sizeof(array); j++) {
        printf("%d", array[j]);
    }
    getchar();
}
</code>```

答:
The type of array is int *, so the size of array in the sense of sizeof(array) is the size of a pointer value (i.e. 4 on 32 bit systems and 8 on 64 bit systems).

You should simply write for (j = 0; j < length; j++) instead of for (j = 0; j < sizeof(array); j++).

Body:
I want to initialize an array of variable length with random zeros and ones. My problem is that the array I created seems to only have a length of 4 elements.
Why is that?

int main()
{
    int i, j;
    int length = 20;
    int *array = (int *) calloc(length, sizeof(int));
    for (i = 1; i < length; i++) {
        array[i] = 1;
        printf("%d", array[i]);
    }
    printf("\n");
    for (j = 0; j < sizeof(array); j++) {
        printf("%d", array[j]);
    }
    getchar();
}


问:
Hide or display checkboxes if checked or not JavaScript
I got a problem with some checkboxes, I don't succeed to filter them according if they are checked or not.

The principle is simple. If I click on "All" all the checkboxes are displayed, but if I click on selected, I just want to see the checkboxes selected and hidde the ones unchecked.

Here is a snippet, please update it in your answer to let me see how it could be done.

Thanks a lot !

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "Juny";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "5";
target[1] = "8";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if(target.indexOf(i)>=0){
    cb.checked =true ;
  }

}
updateText();
function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   * {
       box-sizing: border-box;
   }
   #data {
       padding:5px;
    width:100vw;
   }
   .multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:200px;
   }
   .checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
   }

            label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
   }</code>```

 All | Selected
 <form>

</form>
<textarea id="t"></textarea>```

答:
You can do it with two functions, the first show all parents of inputs, the second hiden all parents of inputs that are not checked.

```<code>function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input:not(:checked)").parent().hide();
}
</code>```

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "Juny";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "5";
target[1] = "8";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }

}
updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input:not(:checked)").parent().hide();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  background-color: #eee;
  width: 100vw;
  white-space: normal;
  height: 200px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}</code>```

All | Selected
<form>

</form>
<textarea id="t"></textarea>```

Body:
I got a problem with some checkboxes, I don't succeed to filter them according if they are checked or not.

The principle is simple. If I click on "All" all the checkboxes are displayed, but if I click on selected, I just want to see the checkboxes selected and hidde the ones unchecked.

Here is a snippet, please update it in your answer to let me see how it could be done.

Thanks a lot !

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "Juny";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "5";
target[1] = "8";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if(target.indexOf(i)>=0){
    cb.checked =true ;
  }

}
updateText();
function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

   * {
       box-sizing: border-box;
   }
   #data {
       padding:5px;
    width:100vw;
   }
   .multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:200px;
   }
   .checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
   }

            label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
   }

 All | Selected
 <form>

</form>
<textarea id="t"></textarea>

Body:
You can do it with two functions, the first show all parents of inputs, the second hiden all parents of inputs that are not checked.

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input:not(:checked)").parent().hide();
}

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "Juny";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "5";
target[1] = "8";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }

}
updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input:not(:checked)").parent().hide();
}

* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  background-color: #eee;
  width: 100vw;
  white-space: normal;
  height: 200px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span onclick="All()" style="cursor:pointer">All</span> | <span onclick="OnlySelecteds()" style="cursor:pointer">Selected</span>
<form>
  <div id="data">
    <div class="multiselect">
      <div id="c_b">
        <div id="checkboxes">
        </div>
      </div>
    </div>
  </div>
</form>
<textarea id="t"></textarea>


问:
MySQL Storing Unlimited Data within Row
What is the best way to store data in this scenario:

ACCOUNT table stores id, username, password and a large set of data comprising of multiple rows. Example: multiple sessions stored with date and other information.

What I'm doing now is creating a new table called sessions_id# for each user, but there has to be a more efficient way.

答:
You are correct in your assumption that there is a better way. What you need is the "relational" in relational databases.

You need only 1 table for the sessions. This table contains columns for the session data, probably a unique ID (use auto-increment) and most important of all, one field where you store the ID of the user the session belongs to.

This is called a one-to-many relationship, because one user can have many sessions, but each session is coupled with only one user.

If you use MyISAM as the DB engine, you will need to keep track of the IDs manually, but if you choose InnoDB as the engine, you can use foreign keys.

You can read more about foreign keys in the MySQL documentation:
http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

Title: MySQL Storing Unlimited Data within Row