问:
Xamarin Android Request to Server is not establishing instead getting an exception?
MainActivity.cs

```<code>    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        Button button = FindViewById<Button>(Resource.Id.Browse);
        button.Click += BrowseButtonOnClick;
    }

    void BrowseButtonOnClick(object sender, EventArgs eventArs)
    {
        Intent = new Intent();
        Intent.SetType("image/*");
        Intent data = Intent.SetAction(Intent.ActionGetContent);

        try
        {
            StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
        }
        catch (ActivityNotFoundException ex)
        {
            Toast.MakeText(this, "Please install a File Manager.", ToastLength.Long).Show();
        }
        catch (Exception ex)
        {
            Toast.MakeText(this, "Error occured ", ToastLength.Long).Show();
        }
    }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
        {
            UploadFile(data);

        }
    }

    void UploadFile(Intent data)
    {
        ICursor cursor = null;

        try
        {
            Button upButton = FindViewById<Button>(Resource.Id.Upload);

            // assuming image
            var docID = DocumentsContract.GetDocumentId(data.Data);
            var id = docID.Split(':')[1];
            var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
            var projections = new string[] { MediaStore.Images.ImageColumns.Data };
            // Try internal storage first
            cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
            if (cursor.Count == 0)
            {
                // not found on internal storage, try external storage
                cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
            }
            var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
            cursor.MoveToFirst();
            var fullPathToImage = cursor.GetString(colData);
            string fpti = cursor.GetString(colData);

            //Toast.MakeText(this, fullPathToImage, ToastLength.Long).Show();

            // Log.Info("MediaPath", fullPathToImage);

            //var client = new HttpClient();
            //Android.Net.Uri uri = data.Data;

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileInputStream fis = new FileInputStream(new File(fullPathToImage)); //uri.Path
            byte[] buf = new byte[1024];
            int n;
            while (-1 != (n = fis.Read(buf)))
                baos.Write(buf, 0, n);

            byte[] vBytes = baos.ToByteArray();

            ByteArrayContent byteContent = new ByteArrayContent(vBytes);
            //var UploadServiceBaseAddress = "http://192.168.3.157:81/Values/UploadFile?file=";
            //StringContent stringContent = new StringContent(UploadServiceBaseAddress, System.Text.Encoding.UTF8);
            string base64 = Convert.ToBase64String(vBytes);

            string strb64 = Convert.ToString(base64);

            upButton.Click += (sender, args) =>
           {
               ProgressDialog progressDialog = new ProgressDialog(this);
               progressDialog.SetTitle("Please wait...");
               progressDialog.SetCancelable(false);

               Task.Run(async () =>
               {
                   try
                   {
                       RunOnUiThread(() =>
                       {
                           progressDialog.Show();

                       });

                       string dataUsed = await SendReceiveTest.Test(strb64);

                       string me = "Uploading...";
                       Toast.MakeText(this, me, ToastLength.Long).Show();

                       RunOnUiThread(() =>
                       {

                         progressDialog.Dismiss();

                       });

                       string msg = "Upload Completed";
                       Toast.MakeText(this, msg, ToastLength.Long).Show();
                       Toast.MakeText(this, dataUsed, ToastLength.Long).Show();

                   }

                   catch (Exception ex)
                   {
                       Log.Error("MediaPath", ex.Message);
                   }

               });

           };
        }
        catch (Exception ex)
        {
            Log.Error("MediaPath", ex.Message);
        }
        finally
        {
            cursor?.Close();
            cursor?.Dispose();
        }
    }

}
</code>```

}

SendReceiveTest.cs

```<code>public static async Task<string> Test(string data)
        {
            try
            {
                using (var client = new HttpClient())
                {

                    var uri = $"http://192.168.3.157:81/Values/UploadFile?file={data}";
                    var response = await client.GetAsync(uri);
                    var stringData = await response.Content.ReadAsStringAsync();
                    //Context c = null;
                    //Toast.MakeText(c, stringData, ToastLength.Long).Show();
                    return stringData;
                }
            }
            catch (Exception ex)
            {
                Log.Error("MediaPath", ex.Message);

            }
            return null;
</code>```

On Exception ex

```<code>{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error getting response stream (ReadDone2): ReceiveFailure ---> System.Exception:   at System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Net.WebConnection.ReadDone (System.IAsyncResult result) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Net.Sockets.SocketAsyncResult+<>c__DisplayClass27_0.<Complete>b__0 (System.Object _) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x0003b] in <a547bd0d78184f26ab08d022f013c1e1>:0
   --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00058] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x003e6] in <b696532a7c264e5e866cb15a1b40a4a4>:0
   --- End of inner exception stack trace ---
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x00449] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at XAFileUpload.SendReceiveTest+<Test>d__0.MoveNext () [0x00066] in C:\Users\sandeepsubbiahs\Documents\Visual Studio 2017\Projects\Xamarin\XAFileUpload\XAFileUpload\SendReceiveTest.cs:28 }
</code>```

On Ex.Message

```<code>"An error occurred while sending the request"
</code>```

On Inner Exception

Internal Status : System.Net.WebExceptionInternalStatus.RequestFatal

Status : System.Net.WebExceptionStatus.ReceiveFailure

I have a 2 button (Browse , Upload) , by clicking 1st button Browse it will pick the picture from Xamarin Android Emulator then after clicking 2nd button Upload It send the picture as base64string to server by using SendReceiveTest class and it's method Test() but getting exception while sending the request to server and which is mentioned above.

答:
Intead of converting image to base64string we can send it just like that using WebClient</p>

```<code>using (WebClient client = new WebClient())
   {
          client.UploadFile(address, fullPathToImage);

   }
</code>```

Body:
MainActivity.cs

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        Button button = FindViewById<Button>(Resource.Id.Browse);
        button.Click += BrowseButtonOnClick;
    }

    void BrowseButtonOnClick(object sender, EventArgs eventArs)
    {
        Intent = new Intent();
        Intent.SetType("image/*");
        Intent data = Intent.SetAction(Intent.ActionGetContent);

        try
        {
            StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
        }
        catch (ActivityNotFoundException ex)
        {
            Toast.MakeText(this, "Please install a File Manager.", ToastLength.Long).Show();
        }
        catch (Exception ex)
        {
            Toast.MakeText(this, "Error occured ", ToastLength.Long).Show();
        }
    }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
        {
            UploadFile(data);

        }
    }

    void UploadFile(Intent data)
    {
        ICursor cursor = null;

        try
        {
            Button upButton = FindViewById<Button>(Resource.Id.Upload);

            // assuming image
            var docID = DocumentsContract.GetDocumentId(data.Data);
            var id = docID.Split(':')[1];
            var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
            var projections = new string[] { MediaStore.Images.ImageColumns.Data };
            // Try internal storage first
            cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
            if (cursor.Count == 0)
            {
                // not found on internal storage, try external storage
                cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
            }
            var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
            cursor.MoveToFirst();
            var fullPathToImage = cursor.GetString(colData);
            string fpti = cursor.GetString(colData);

            //Toast.MakeText(this, fullPathToImage, ToastLength.Long).Show();

            // Log.Info("MediaPath", fullPathToImage);

            //var client = new HttpClient();
            //Android.Net.Uri uri = data.Data;

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileInputStream fis = new FileInputStream(new File(fullPathToImage)); //uri.Path
            byte[] buf = new byte[1024];
            int n;
            while (-1 != (n = fis.Read(buf)))
                baos.Write(buf, 0, n);

            byte[] vBytes = baos.ToByteArray();

            ByteArrayContent byteContent = new ByteArrayContent(vBytes);
            //var UploadServiceBaseAddress = "http://192.168.3.157:81/Values/UploadFile?file=";
            //StringContent stringContent = new StringContent(UploadServiceBaseAddress, System.Text.Encoding.UTF8);
            string base64 = Convert.ToBase64String(vBytes);

            string strb64 = Convert.ToString(base64);

            upButton.Click += (sender, args) =>
           {
               ProgressDialog progressDialog = new ProgressDialog(this);
               progressDialog.SetTitle("Please wait...");
               progressDialog.SetCancelable(false);

               Task.Run(async () =>
               {
                   try
                   {
                       RunOnUiThread(() =>
                       {
                           progressDialog.Show();

                       });

                       string dataUsed = await SendReceiveTest.Test(strb64);

                       string me = "Uploading...";
                       Toast.MakeText(this, me, ToastLength.Long).Show();

                       RunOnUiThread(() =>
                       {

                         progressDialog.Dismiss();

                       });

                       string msg = "Upload Completed";
                       Toast.MakeText(this, msg, ToastLength.Long).Show();
                       Toast.MakeText(this, dataUsed, ToastLength.Long).Show();

                   }

                   catch (Exception ex)
                   {
                       Log.Error("MediaPath", ex.Message);
                   }

               });

           };
        }
        catch (Exception ex)
        {
            Log.Error("MediaPath", ex.Message);
        }
        finally
        {
            cursor?.Close();
            cursor?.Dispose();
        }
    }

}

}

SendReceiveTest.cs

public static async Task<string> Test(string data)
        {
            try
            {
                using (var client = new HttpClient())
                {

                    var uri = $"http://192.168.3.157:81/Values/UploadFile?file={data}";
                    var response = await client.GetAsync(uri);
                    var stringData = await response.Content.ReadAsStringAsync();
                    //Context c = null;
                    //Toast.MakeText(c, stringData, ToastLength.Long).Show();
                    return stringData;
                }
            }
            catch (Exception ex)
            {
                Log.Error("MediaPath", ex.Message);

            }
            return null;

On Exception ex

{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error getting response stream (ReadDone2): ReceiveFailure ---> System.Exception:   at System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Net.WebConnection.ReadDone (System.IAsyncResult result) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Net.Sockets.SocketAsyncResult+<>c__DisplayClass27_0.<Complete>b__0 (System.Object _) [0x00000] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.WebConnection.HandleError (System.Net.WebExceptionStatus st, System.Exception e, System.String where) [0x0003b] in <a547bd0d78184f26ab08d022f013c1e1>:0
   --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00058] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x003e6] in <b696532a7c264e5e866cb15a1b40a4a4>:0
   --- End of inner exception stack trace ---
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x00449] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at XAFileUpload.SendReceiveTest+<Test>d__0.MoveNext () [0x00066] in C:\Users\sandeepsubbiahs\Documents\Visual Studio 2017\Projects\Xamarin\XAFileUpload\XAFileUpload\SendReceiveTest.cs:28 }

On Ex.Message

"An error occurred while sending the request"

On Inner Exception

Internal Status : System.Net.WebExceptionInternalStatus.RequestFatal

Status : System.Net.WebExceptionStatus.ReceiveFailure

I have a 2 button (Browse , Upload) , by clicking 1st button Browse it will pick the picture from Xamarin Android Emulator then after clicking 2nd button Upload It send the picture as base64string to server by using SendReceiveTest class and it's method Test() but getting exception while sending the request to server and which is mentioned above.

Body:
Intead of converting image to base64string we can send it just like that using WebClient

using (WebClient client = new WebClient())
   {
          client.UploadFile(address, fullPathToImage);

   }


来源: stackexchange

问:
Why use this construct - PropertyChangedEventHandler handler = this.PropertyChanged?
The article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx has the following code sample:

```<code>public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = this.PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(this, e);
    }
}
</code>```

My question is what is gained by introducing the variable 'handler' - the following code seems to work fine:

```<code>public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged!= null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        PropertyChanged(this, e);
    }
}
</code>```

答:
The reasoning behind the local variable is that in a multi-threaded environment, the event could be devoid of subscribers (ie, become null) in the gap between checking for null and firing the event.

By taking a local variable, you are avoiding this potential issue - checking the event in a thread-safe way.  It does raise the issue that the event might be thrown for an item that had previously unhooked.

ContentLicense: CC BY-SA 2.5

Body:
The article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx has the following code sample:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = this.PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(this, e);
    }
}

My question is what is gained by introducing the variable 'handler' - the following code seems to work fine:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged!= null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        PropertyChanged(this, e);
    }
}


问:
How can I start flyway migration before hibernate validation?
I use flyway + hibernate validate. I have flyway bean:

```<code>@Component
public class DbMigration {

    private static final Logger LOG = LoggerFactory.getLogger(DbMigration.class);

    private final Config config;

    @Autowired
    public DbMigration(Config config) {
        this.config = config;
    }

    public void runMigration() {
        try {
            Flyway flyway = new Flyway();
            flyway.configure(properties());
            int migrationApplied = flyway.migrate();
            LOG.info("[" + migrationApplied + "] migrations are applied");
        } catch (FlywayException ex) {
            throw new DatabaseException("Exception during database migrations: ", ex);
        }
    }

    public Properties properties() {
        //my prop
    }
}
</code>```

And in Apllication class I do it:

```<code>public static void main(String[] args) {
        try {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
            context.getBean(DbMigration.class).runMigration();
</code>```

But my hibernate start before runMigration(); And validate throw exeption. How can I start next?

run Migration

start hibernate validation

EDIT:

```<code>  @Bean
    @Autowired
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource datasource) {
        log.info("entityManagerFactory start");
        dbMigration.runMigration();
</code>```

But I think it is bad

答:
In your spring application configuration, if you have an entity manager factory bean configuration you can make it depend on the flyway bean so that it gets initialized after it. Something like:

```<code>@Bean
@DependsOn("flyway")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    // Initialize EntityManagerFactory here
}
</code>```

The flyway bean configuration can be something like:

```<code>@Bean(initMethod = "migrate")
public Flyway flyway() {
    Flyway flyway = new Flyway();
    // configure bean here
    return flyway;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use flyway + hibernate validate. I have flyway bean:

@Component
public class DbMigration {

    private static final Logger LOG = LoggerFactory.getLogger(DbMigration.class);

    private final Config config;

    @Autowired
    public DbMigration(Config config) {
        this.config = config;
    }

    public void runMigration() {
        try {
            Flyway flyway = new Flyway();
            flyway.configure(properties());
            int migrationApplied = flyway.migrate();
            LOG.info("[" + migrationApplied + "] migrations are applied");
        } catch (FlywayException ex) {
            throw new DatabaseException("Exception during database migrations: ", ex);
        }
    }

    public Properties properties() {
        //my prop
    }
}

And in Apllication class I do it:

public static void main(String[] args) {
        try {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
            context.getBean(DbMigration.class).runMigration();

But my hibernate start before runMigration(); And validate throw exeption. How can I start next?

run Migration

start hibernate validation

EDIT:

  @Bean
    @Autowired
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource datasource) {
        log.info("entityManagerFactory start");
        dbMigration.runMigration();

But I think it is bad

Body:
In your spring application configuration, if you have an entity manager factory bean configuration you can make it depend on the flyway bean so that it gets initialized after it. Something like:

@Bean
@DependsOn("flyway")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    // Initialize EntityManagerFactory here
}

The flyway bean configuration can be something like:

@Bean(initMethod = "migrate")
public Flyway flyway() {
    Flyway flyway = new Flyway();
    // configure bean here
    return flyway;
}


问:
Disable form but keep each of its elements look like enabled
I would like to disable the whole Form but still, keep each of this Form elements like TextBox, Buttons etc to look like enabled.

So, I want to block user interactions on those elements, but preserve it's standard look, not grayed out etc.

Can that be done in kind of automatic way or one just need to manually handle EnabledChanged events for each of affected controls?

答:
For all the controls, the "backcolor" property is set to window by default. Select all of them and set to white (or the desired color) to get the same appearance.
You might want to do the same with text and border color. Its all about the level of customization you want.

To have complete control over the colors, you will need to redraw them.

```<code>protected override void OnPaint ( System.Windows.Forms.PaintEventArgs e )
{
    if ( Enabled )
    {
        //use normal realization
        base.OnPaint (e);
        return;
    }
    //custom drawing
    using ( Brush aBrush = new SolidBrush( "YourCustomDisableColor" ) )
    {
        e.Graphics.DrawString( Text, Font, aBrush, ClientRectangle );
    }
}
</code>```

Body:
For all the controls, the "backcolor" property is set to window by default. Select all of them and set to white (or the desired color) to get the same appearance.
You might want to do the same with text and border color. Its all about the level of customization you want.

To have complete control over the colors, you will need to redraw them.

protected override void OnPaint ( System.Windows.Forms.PaintEventArgs e )
{
    if ( Enabled )
    {
        //use normal realization
        base.OnPaint (e);
        return;
    }
    //custom drawing
    using ( Brush aBrush = new SolidBrush( "YourCustomDisableColor" ) )
    {
        e.Graphics.DrawString( Text, Font, aBrush, ClientRectangle );
    }
}


问:
Rails + PostgreSQL + rbenv-vars: fe_sendauth: no password supplied using environment variables
I'm working on a Rails project which uses PostgreSQL and I want to store the database login details in a file and access them with environment variables using rbenv-vars. I'm running Ubuntu 16.10.

Considering the following files:

pg_hba.conf

```<code># Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5
</code>```

database.yml

```<code>default: &default
  adapter: postgresql
  encoding: unicode
  host: localhost
  pool: 5
  username: consul
  password: <% ENV['CONSUL_DATABASE_PASSWORD'] %>
</code>```

.rbenv-vars

```<code>SECRET_KEY_BASE=(secret key)
CONSUL_DATABASE_PASSWORD=(database password)
</code>```

When I try to create the database for the project using the rake db:create command I get this error:

```<code>fe_sendauth: no password supplied
</code>```

I tried storing the password in cleartext and it works, but as you can imagine, I don't want to do that.

答:
Change the line to

```<code>password: <%= ENV['CONSUL_DATABASE_PASSWORD'] %>
</code>```

<% %> just evaluate the content whereas

<%= %> evaluates and insert the content in the place of the tag

Refer this answer for more details on erb tags What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

Body:
I'm working on a Rails project which uses PostgreSQL and I want to store the database login details in a file and access them with environment variables using rbenv-vars. I'm running Ubuntu 16.10.

Considering the following files:

pg_hba.conf

# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5

database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  host: localhost
  pool: 5
  username: consul
  password: <% ENV['CONSUL_DATABASE_PASSWORD'] %>

.rbenv-vars

SECRET_KEY_BASE=(secret key)
CONSUL_DATABASE_PASSWORD=(database password)

When I try to create the database for the project using the rake db:create command I get this error:

fe_sendauth: no password supplied

I tried storing the password in cleartext and it works, but as you can imagine, I don't want to do that.

Body:
Change the line to

password: <%= ENV['CONSUL_DATABASE_PASSWORD'] %>

<% %> just evaluate the content whereas

<%= %> evaluates and insert the content in the place of the tag

Refer this answer for more details on erb tags What is the difference between <%, <%=, <%# and -%> in ERB in Rails?


问:
How to boost relevance for exact match results when using wildcard in sphinx?
This is my search request:

```<code>    (new SphinxSearch())
        ->search((new SphinxClient())->escapeString($query) . '*', 'services')
        ->setMatchMode(SphinxClient::SPH_MATCH_EXTENDED)
        ->setFieldWeights([
            'name' => 10,
            'legal_name' => 10,
            'description' => 10,
            'keywords' => 10,
            'category_name' => 3,
            'categories' => 3,
        ])
        ->setSortMode(SphinxClient::SPH_SORT_EXTENDED, "@weight DESC")
        ->setRankingMode(SphinxClient::SPH_RANK_SPH04)
        ->get(true);
</code>```

And here is index config:

```<code>index services
{
    source = services
    path = /var/lib/sphinxsearch/data/services
    docinfo = extern
    morphology = stem_enru
    min_stemming_len = 1
    min_word_len = 1
    min_infix_len = 1
    html_strip = 1
    index_exact_words = 1
    expand_keywords = 1
    mlock = 0
    charset_table = 0..9, A..Z->a..z, _, *, -, a..z, \
                        U+2C->U+2E, U+2E, U+0044, U+0046, U+0130, U+0401->U+0435, U+0451->U+0435, U+410..U+42F->U+430..U+44F, U+430..U+44F
}
</code>```

For a query "school №4" it returns all relevant results, but with something like "school №42" at the top and the exact match of "school №4" is close to the bottom of the result set.

Well, it's not actually an exact match - in the service name there may be some other words and symbols. But it's closest to what user entered in the search field, so I believe it should be more relevant than results with a wild card.

How can I move "exact" match to the top of the set?

P.S. I'm using this Laravel specific wrapper for SphinxClient, though I don't think it's important.

答: Current solution that I have - make two queries with and without wildcard and then merge results with exact matches on the top. It works, but not ideal, obviously.</p>

Body:
This is my search request:

    (new SphinxSearch())
        ->search((new SphinxClient())->escapeString($query) . '*', 'services')
        ->setMatchMode(SphinxClient::SPH_MATCH_EXTENDED)
        ->setFieldWeights([
            'name' => 10,
            'legal_name' => 10,
            'description' => 10,
            'keywords' => 10,
            'category_name' => 3,
            'categories' => 3,
        ])
        ->setSortMode(SphinxClient::SPH_SORT_EXTENDED, "@weight DESC")
        ->setRankingMode(SphinxClient::SPH_RANK_SPH04)
        ->get(true);

And here is index config:

index services
{
    source = services
    path = /var/lib/sphinxsearch/data/services
    docinfo = extern
    morphology = stem_enru
    min_stemming_len = 1
    min_word_len = 1
    min_infix_len = 1
    html_strip = 1
    index_exact_words = 1
    expand_keywords = 1
    mlock = 0
    charset_table = 0..9, A..Z->a..z, _, *, -, a..z, \
                        U+2C->U+2E, U+2E, U+0044, U+0046, U+0130, U+0401->U+0435, U+0451->U+0435, U+410..U+42F->U+430..U+44F, U+430..U+44F
}

For a query "school №4" it returns all relevant results, but with something like "school №42" at the top and the exact match of "school №4" is close to the bottom of the result set.

Well, it's not actually an exact match - in the service name there may be some other words and symbols. But it's closest to what user entered in the search field, so I believe it should be more relevant than results with a wild card.

How can I move "exact" match to the top of the set?

P.S. I'm using this Laravel specific wrapper for SphinxClient, though I don't think it's important.


问:
how can filter multilevel arrays for searching a string?
```<code>NSPredicate *predicate3 = [NSPredicate predicateWithFormat:@"ANY %K.%K.%K CONTAINS[c] %@",@"Assets",@"TFloorAssets",@"AssetNo",strSearch];

NSArray *filteredPendingList = [NSMutableArray arrayWithArray:[arrOfAllAssetsCategory filteredArrayUsingPredicate:predicate3]];
</code>```

I am using above type of code for multilevel search ?

答:
Use "compound predicate" like below</p>

```<code>NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:
                          @[predicateEventsByAsset, predicateEventsByFloorAsset ,predicateEventsByAssetNo]];
self.filteredEventsArray = [self.eventsArray filteredArrayUsingPredicate:predicate];
</code>```

Body:
NSPredicate *predicate3 = [NSPredicate predicateWithFormat:@"ANY %K.%K.%K CONTAINS[c] %@",@"Assets",@"TFloorAssets",@"AssetNo",strSearch];

NSArray *filteredPendingList = [NSMutableArray arrayWithArray:[arrOfAllAssetsCategory filteredArrayUsingPredicate:predicate3]];

I am using above type of code for multilevel search ?

Body:
Use "compound predicate" like below

NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:
                          @[predicateEventsByAsset, predicateEventsByFloorAsset ,predicateEventsByAssetNo]];
self.filteredEventsArray = [self.eventsArray filteredArrayUsingPredicate:predicate];


问:
Exclusion in sonar property file also in Analysis properties
How to add exclusions in sonar "Analysis properties" in jenkins even exclusion available in sonar property file.

We have exclusions in property file, and we added exclusion in "Analysis properties" in jenkins. But while scanning it is excluding only the files given in "Analysis properties", but not from the property file.

we want the exclusion given both in Property file as well as from the "Analysis properties" field.

Please help.

答:
Properties are not cumulative. As described at the top of this page, there is a fallback structure and the first-found value is the one that's used from this order of checking:

command line

properties file

project-level properties defined in the UI

global-level properties


问:
PHP/MySQL Show first X results, hide the rest
Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? I just need to know how to show only the first X results in one page, then the rest in a seperate page using href.

My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.Thanks

答:
Actually you are searching for Pagination. There are some useful jQuery paginations plugins:

jQuery pagination plugin

DataTables Plugin

Or using PHP:

Pagination in PHP


问:
How can I fetch an unmerged pull request for a branch I don't own?
I need to pull in a specific pull request (that hasn't been processed into the main stream yet) in the NServiceBus repo:

https://github.com/johnsimons/NServiceBus/commit/d8524d53094e8181716e771c1023e968132abc15

It's obviously not my repo, but I need the changes that exist in that pull request.

What is the best way to do this?

答:
Once you added the upstream repo as an upstream remote (as @elias pointed out):

```<code>$ git remote add upstream git@github.com:Particular/NServiceBus
</code>```

You can configure git to fetch pull requests by default:

```<code>$ git config --local --add remote.upstream.fetch '+refs/pull/*/head:refs/remotes/upstream/pr/*'
</code>```

So, let's fetch it:

```<code>$ git fetch upstream
Fetching upstream
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 2), reused 4 (delta 2), pack-reused 0
Unpacking objects: 100% (4/4), done.
From https://github.com/Particular/NServiceBus
 * [new ref]         refs/pull/1/head -> upstream/pr/1
 * [new ref]         refs/pull/2/head -> upstream/pr/2
</code>```

And check it out:

```<code>$ git checkout pr/2
Branch pr/2 set up to track remote branch pr/2 from upstream.
Switched to a new branch 'pr/2'
</code>```

Body:
Once you added the upstream repo as an upstream remote (as @elias pointed out):

$ git remote add upstream git@github.com:Particular/NServiceBus

You can configure git to fetch pull requests by default:

$ git config --local --add remote.upstream.fetch '+refs/pull/*/head:refs/remotes/upstream/pr/*'

So, let's fetch it:

$ git fetch upstream
Fetching upstream
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 2), reused 4 (delta 2), pack-reused 0
Unpacking objects: 100% (4/4), done.
From https://github.com/Particular/NServiceBus
 * [new ref]         refs/pull/1/head -> upstream/pr/1
 * [new ref]         refs/pull/2/head -> upstream/pr/2

And check it out:

$ git checkout pr/2
Branch pr/2 set up to track remote branch pr/2 from upstream.
Switched to a new branch 'pr/2'


问:
How to check whether a given file is a valid video file in C++?
I tried to do it using OpenCV:

```<code>std::string input_name = "<path to file>";
cv::VideoCapture cap(input_name);
if(!cap.isOpened()) printf("Invalid video\n");
</code>```

However, when I try passing a .txt file, VideoCapture reads it successfully for unknown reasons. When I try to find the number of frames in the video,

```<code>if(cap.get(cv::CV_CAP_PROP_FRAME_COUNT) == 0) printf("Invalid video\n");
</code>```

I get a different number of frames each time I execute. I also tried finding the width and height of a frame in the file,

```<code>cv::Mat Frame;
if(!cap.read(Frame)) printf("Cannot read frame\n");
else
{
    printf("Frame width is %d\n", Frame.cols);
    printf("Frame height is %d\n", Frame.rows);
}
</code>```

their values are 640 and 400 respectively. Why is this happening? Is there a way to check if a given file is a valid video file preferably using OpenCV?

答:
The only really good way to determine if a file is "valid", is to read its  content with an appropriate reader-function that understands that very format. There is no simple, universal marker to say "this is a genuine video file, and can't be something else" - and even if there was, someone could on purpose or by mistake put that in the file so that it looks like a "real video", but isn't when you read the rest of the information. Since there are dozens of different video file formats, it's hard to do something more sensible than "try it, see what happens".

As discussed in another answer, cv::VideoCapture::read() will read the file and return an error indication if the file is not valid. If you want to distinguish between "file doesn't exist", you could do some checking before you try to read it, so you can say "file doesn't exist" as opposed to "sorry, but it seems like that's not a valid video file" - although the latter does apply to "there is no such file" too.

Note that I expect cv::VideoCapture to say isOpened() if the file exists, so for a text-file or PDF, it will happily accept that as "opened". You have to actually try to READ the file to tell if it's a video file. However, the documentation for both ::get and ::read is pretty useless in respect of "What happens on bad input", it almost seems like the functions are designed to only work with valid input.

Body:
I tried to do it using OpenCV:

std::string input_name = "<path to file>";
cv::VideoCapture cap(input_name);
if(!cap.isOpened()) printf("Invalid video\n");

However, when I try passing a .txt file, VideoCapture reads it successfully for unknown reasons. When I try to find the number of frames in the video,

if(cap.get(cv::CV_CAP_PROP_FRAME_COUNT) == 0) printf("Invalid video\n");

I get a different number of frames each time I execute. I also tried finding the width and height of a frame in the file,

cv::Mat Frame;
if(!cap.read(Frame)) printf("Cannot read frame\n");
else
{
    printf("Frame width is %d\n", Frame.cols);
    printf("Frame height is %d\n", Frame.rows);
}

their values are 640 and 400 respectively. Why is this happening? Is there a way to check if a given file is a valid video file preferably using OpenCV?


问:
Is there any alternate to acquire dependencies without using POM.xml?
My question is, I don't want to write XML code for dependencies in the POM.xml again and again.
For example, I want to use the log4j JAR in my project. instead of writing XML code is there any option to download the related JAR files?

答:
Of course you can download (or copy) these jars, and then manually add them to your build path.
For instance in eclipse, you can select all the libraries under the "Maven Dependiences" and copy them to other folder eg. in other project. Then you need to select these libraries and using the right mouse button add them to build path, done :)</p>


问:
Find largest adjacent product in array (JavaScript)
I'm trying to understand the following solution for finding the largest adjacent product in any given array.

Example:

```<code> For inputArray = [3, 6, -2, -5, 7, 3], the output should be
 adjacentElementsProduct(inputArray) = 21.

 7 and 3 produce the largest product.
</code>```

Possible solution in JS:

```<code>function adjacentElementsProduct(arr) {
  return Math.max(...arr.slice(1).map((x,i)=>[x*arr[i]]))
  }
</code>```

I am having a hard time understanding two things:

What do the three dots exactly do and how does this get passed into the function? Is there any way to write this in a more understandable way? I know that is the "spread syntax" feature in ES6, but still don't understand completely.

Why do we insert "1" as argument to slice? My first though was to input "0", because we want to start at the start, then loop through everything, and see which adjacent product is the largest.

I'd appreciate any advice, links and explanations.

Thanks.

Cheers!

答:
1. What do the three dots exactly do and how does this get passed into the function? Is there any way to write this in a more understandable way? I know that is some kind of "spread" feature in ES6, but still don't understand completely.

The Math#max needs a list of numbers as parameters, and map produces an array. The spread syntax is used to convert an array to be expanded to a list of parameters.

const arr = [1, 2, 3];

console.log('max on array', Math.max(arr));

console.log('max on list of parameters', Math.max(...arr));```
</div>
</div>
</p>

<p>In this case you can use <code>Function#apply</code> to convert the array to a list of parameters. I find it less readable, however.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [1, 2, 3];

console.log(Math.max.apply(Math, arr));</code>```

2. Why do we insert "1" as argument to slice? My first though was to input "0", because we want to start at the start, then loop through everything, and see which adjacent product is the largest.

Lets break down the iteration order of the 2 arrays.

```<code>[3, 6, -2, -5, 7, 3] // inputArray
[6, -2, -5, 7, 3] // inputArray.slice(1)
</code>```

Now on each iteration of inputArray.slice(1):

```<code>x: 6, i = 0, arr[0] = 3
x: -2, i = 1, arr[1] = 6
x: -5, i = 2, arr[2] = -2
</code>```

Since the inputArray.slice(1) array starts from the 2nd element of the inputArray, the index (i) points to the 1st element of the inputArray. And the result is an array of products of 2 adjacent numbers.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to understand the following solution for finding the largest adjacent product in any given array.

Example:

 For inputArray = [3, 6, -2, -5, 7, 3], the output should be
 adjacentElementsProduct(inputArray) = 21.

 7 and 3 produce the largest product.

Possible solution in JS:

function adjacentElementsProduct(arr) {
  return Math.max(...arr.slice(1).map((x,i)=>[x*arr[i]]))
  }

I am having a hard time understanding two things:

What do the three dots exactly do and how does this get passed into the function? Is there any way to write this in a more understandable way? I know that is the "spread syntax" feature in ES6, but still don't understand completely.

Why do we insert "1" as argument to slice? My first though was to input "0", because we want to start at the start, then loop through everything, and see which adjacent product is the largest.

I'd appreciate any advice, links and explanations.

Thanks.

Cheers!

Body:
1. What do the three dots exactly do and how does this get passed into the function? Is there any way to write this in a more understandable way? I know that is some kind of "spread" feature in ES6, but still don't understand completely.

The Math#max needs a list of numbers as parameters, and map produces an array. The spread syntax is used to convert an array to be expanded to a list of parameters.

const arr = [1, 2, 3];

console.log('max on array', Math.max(arr));

console.log('max on list of parameters', Math.max(...arr));

In this case you can use Function#apply to convert the array to a list of parameters. I find it less readable, however.

const arr = [1, 2, 3];

console.log(Math.max.apply(Math, arr));

2. Why do we insert "1" as argument to slice? My first though was to input "0", because we want to start at the start, then loop through everything, and see which adjacent product is the largest.

Lets break down the iteration order of the 2 arrays.

[3, 6, -2, -5, 7, 3] // inputArray
[6, -2, -5, 7, 3] // inputArray.slice(1)

Now on each iteration of inputArray.slice(1):

x: 6, i = 0, arr[0] = 3
x: -2, i = 1, arr[1] = 6
x: -5, i = 2, arr[2] = -2

Since the inputArray.slice(1) array starts from the 2nd element of the inputArray, the index (i) points to the 1st element of the inputArray. And the result is an array of products of 2 adjacent numbers.


问:
Vue js router-view selection
I have parent component which has

```<code><router-view></router-view>
</code>```

Inside of parent component there is another component and it also has a

```<code><router-view></router-view>
</code>```

Both are bound to /login route

When I go to /login route it loads both of them. I would like to skip first/parent router-view for loading the component.
How can i achieve this? I can think of setting some state and prevent loading with v-if directive but that seems kind of wrong.

Maybe another solution, can i pass null to a parent named view on specific route?

答:
Found a solution in case of somebody needs:

```<code><-- applies only this one -->
<router-view name="login"></router-view>

<router-view></router-view>

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        login: LoginComp
      }
    }
  ]
})
</code>```

Ref : https://router.vuejs.org/en/essentials/named-views.html

Title: Vue js router-view selection

Body:
I have parent component which has

<router-view></router-view>

Inside of parent component there is another component and it also has a

<router-view></router-view>

Both are bound to /login route

When I go to /login route it loads both of them. I would like to skip first/parent router-view for loading the component.
How can i achieve this? I can think of setting some state and prevent loading with v-if directive but that seems kind of wrong.

Maybe another solution, can i pass null to a parent named view on specific route?

Body:
Found a solution in case of somebody needs:

<-- applies only this one -->
<router-view name="login"></router-view>

<router-view></router-view>

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        login: LoginComp
      }
    }
  ]
})

Ref : https://router.vuejs.org/en/essentials/named-views.html


答: This is done for thread safety. In the second example is it possible that the invocation list of PropertyChanged could become null during the if block, resulting in an exception.</p>

Title: Why use this construct - PropertyChangedEventHandler handler = this.PropertyChanged?


问:
schedule an email using php and mysql without opening/accessing the website/webpage
how can i run the code below with out opening the website/domain. i have tried to use cron jobs but still i need to open the website and refresh the page.</p>

```<code><?php

    $currentDate = date("d m Y");
    $setDate = date("04 08 Y");

    if ($setDate == $currentDate) {
        $to = "somebody@example.com";
        $subject = "My subject";
        $txt = "Hello world!";
        $headers = "From: webmaster@example.com";

        mail($to,$subject,$txt,$headers);
        echo "email notification sent";
     }else{
        echo "email not sent";
    }
?>
</code>```

答:
The problem is i am on shared hosting and running the code once per minute is not allowed. so i change it to */15 * * * *.

not allowed on hostgator shared hosting

```<code>*/1 *   *   *   */opt/php55/bin/php /home/username/public_html/cron.php >/dev/null 2>&1
</code>```

working command

```<code>*/15    *   *   *   */opt/php55/bin/php /home/username/public_html/cron.php >/dev/null 2>&1
</code>```

Time intervals for hostgator

Body:
how can i run the code below with out opening the website/domain. i have tried to use cron jobs but still i need to open the website and refresh the page.

<?php

    $currentDate = date("d m Y");
    $setDate = date("04 08 Y");

    if ($setDate == $currentDate) {
        $to = "somebody@example.com";
        $subject = "My subject";
        $txt = "Hello world!";
        $headers = "From: webmaster@example.com";

        mail($to,$subject,$txt,$headers);
        echo "email notification sent";
     }else{
        echo "email not sent";
    }
?>

Body:
The problem is i am on shared hosting and running the code once per minute is not allowed. so i change it to */15 * * * *.

not allowed on hostgator shared hosting

*/1 *   *   *   */opt/php55/bin/php /home/username/public_html/cron.php >/dev/null 2>&1

working command

*/15    *   *   *   */opt/php55/bin/php /home/username/public_html/cron.php >/dev/null 2>&1

Time intervals for hostgator


问:
Can I pass a property list as &key arguments to a function?
Is there's a way to pass to a function a property list as argument in a way similar to this:</p>

```<code>(defun sum (&key x y) (+ x y))
(sum '(:x 10 :y 20))
</code>```

答:
To call a function with the arguments coming from a list use APPLY:

```<code>CL-USER > (apply #'sum '(:x 10 :y 20))
30
</code>```

Also this works:

```<code>CL-USER > (apply #'sum :x '(10 :y 20))
30

CL-USER > (apply #'sum :x 10 '(:y 20))
30

CL-USER > (apply #'sum :x 10 :y '(20))
30

CL-USER > (apply #'sum :x 10 :y 20 '())
30
</code>```

Note that the variable call-arguments-limit still applies. The number of arguments in a function call that an implementation supports is usually limited. Thus applying a function with a long list of arguments might not work. Note that for example in ABCL this value is just 50 (fifty).

Body:
Is there's a way to pass to a function a property list as argument in a way similar to this:

(defun sum (&key x y) (+ x y))
(sum '(:x 10 :y 20))

Body:
To call a function with the arguments coming from a list use APPLY:

CL-USER > (apply #'sum '(:x 10 :y 20))
30

Also this works:

CL-USER > (apply #'sum :x '(10 :y 20))
30

CL-USER > (apply #'sum :x 10 '(:y 20))
30

CL-USER > (apply #'sum :x 10 :y '(20))
30

CL-USER > (apply #'sum :x 10 :y 20 '())
30

Note that the variable call-arguments-limit still applies. The number of arguments in a function call that an implementation supports is usually limited. Thus applying a function with a long list of arguments might not work. Note that for example in ABCL this value is just 50 (fifty).


问:
Odoo 10 use configuration value (stored in ir.values) inside XML
I want to create a menu in the sidebar which shows products of a specific category. I was thinking to use a filter for this task, which is set by default.

However, I don't know how to use the value of my configuration inside my XML domain.

Here is how my XML code looks like:

```<code><record id="my_product_search_form_view" model="ir.ui.view">
    <field name="name">Products Of My Category Search</field>
    <field name="model">product.template</field>
    <field name="inherit_id" ref="product.product_template_search_view" />
    <field name="arch" type="xml">
        <xpath expr="//search" position="inside">
            <filter string="My Category" name="filter_my_categ" domain="[('categ_id','child_of',my_category)]"/>
        </xpath>
    </field>
</record>

<record id="my_product_action" model="ir.actions.act_window">
    <field name="name">Products Of My Category</field>
    <field name="type">ir.actions.act_window</field>
    <field name="res_model">product.template</field>
    <field name="view_mode">kanban,tree,form</field>
    <field name="context">{"search_default_filter_my_categ":1}</field>
    <field name="search_view_id" ref="my_product_search_form_view" />
</record>

<menuitem id="menu_my_products" name="Products Of my Category"
      parent="menu_product" action="my_product_action"
       />
</code>```

I hoped, that when adding 'my_category' to the ir.values table with the model 'product.template' the value will somehow be added to the context - which is not the case & I get an Odoo Client Error NameError: name 'my_category' is not defined

Does anyone know how I can use values of the ir.values table inside my XML view - or at least call a python method inside the context or domain tags? Or is there another solution for my task? Thanks for your help!

答:
I tried this in odoo v8 and it works for me.

First create your filter without domain only with context.

```<code><filter string="My Category" name="filter_my_categ" domain="[]" context="{'custom_filter':1}"/>
</code>```

Then i inherited the search method like this.

```<code>def search(self, cr, uid, args, offset=0, limit=None, order=None,context=None, count=False):
        if context.get('custom_filter',False):
            state = self.pool.get('ir.values').get_default(cr, uid, 'sale.order', 'dyn_filter')
            args.append(['state','=',state])
        result= super(sale_order_ext, self).search(cr, uid, args=args, offset=offset, limit=limit, order=order,
            context=context, count=count)

    return result
</code>```

That's all.
Thank you.

Body:
I want to create a menu in the sidebar which shows products of a specific category. I was thinking to use a filter for this task, which is set by default.

However, I don't know how to use the value of my configuration inside my XML domain.

Here is how my XML code looks like:

<record id="my_product_search_form_view" model="ir.ui.view">
    <field name="name">Products Of My Category Search</field>
    <field name="model">product.template</field>
    <field name="inherit_id" ref="product.product_template_search_view" />
    <field name="arch" type="xml">
        <xpath expr="//search" position="inside">
            <filter string="My Category" name="filter_my_categ" domain="[('categ_id','child_of',my_category)]"/>
        </xpath>
    </field>
</record>

<record id="my_product_action" model="ir.actions.act_window">
    <field name="name">Products Of My Category</field>
    <field name="type">ir.actions.act_window</field>
    <field name="res_model">product.template</field>
    <field name="view_mode">kanban,tree,form</field>
    <field name="context">{"search_default_filter_my_categ":1}</field>
    <field name="search_view_id" ref="my_product_search_form_view" />
</record>

<menuitem id="menu_my_products" name="Products Of my Category"
      parent="menu_product" action="my_product_action"
       />

I hoped, that when adding 'my_category' to the ir.values table with the model 'product.template' the value will somehow be added to the context - which is not the case & I get an Odoo Client Error NameError: name 'my_category' is not defined

Does anyone know how I can use values of the ir.values table inside my XML view - or at least call a python method inside the context or domain tags? Or is there another solution for my task? Thanks for your help!

Body:
I tried this in odoo v8 and it works for me.

First create your filter without domain only with context.

<filter string="My Category" name="filter_my_categ" domain="[]" context="{'custom_filter':1}"/>

Then i inherited the search method like this.

def search(self, cr, uid, args, offset=0, limit=None, order=None,context=None, count=False):
        if context.get('custom_filter',False):
            state = self.pool.get('ir.values').get_default(cr, uid, 'sale.order', 'dyn_filter')
            args.append(['state','=',state])
        result= super(sale_order_ext, self).search(cr, uid, args=args, offset=offset, limit=limit, order=order,
            context=context, count=count)

    return result

That's all.
Thank you.


问:
xamarin form next back button fixed bar
I am newbie to Xamarin forms and I have to implement something like bellow.
where in very bottom of the page there is a next button and back button and in the middle of the page having some page indicator where current page is rely.

what my question is I need to change the page content upon click in next and back button ? how do I can start doing something like this ?

In simple term are there like xamarin form page where it having container to embedded view to that page dynamically.

答: If I understood correctly - you need Carousel View. Please read  these articles -article1, article2, article3. Choose something that suits you.</p>

Title: xamarin form next back button fixed bar


问:
Advice Requested: Keeping list of NuGet Pkgs
2 questions in bold below. Background information is in normal weight.

I'm looking for advice on how to best maintain a list of useful NuGet packages. I am new to .Net development and, as such, only know about a limited number of packages (eg: bower), but I can see how it might be useful to maintain a list of packages that all or most of my applications will employ.

In my case, I expect to only develop responsive web sites/applications (no APIs, expected), so bootstrap and bower are probably a "must", but as I find more and more packages useful, does anyone have any advice to share on how you remember/keep track of which packages you will reuse in many projects?

Obviously, I can just keep a list in an excel file, OneNote, Word, whatever, but I am looking for experienced advice, in case there's a better way of which I am unaware.

Secondly, is there a way to have the same list of NuGet packages automatically installed into new solutions as you create them, without having to go through a list and install manually?

答:
does anyone have any advice to share on how you remember/keep track of which packages you will reuse in many projects?

Package.config should be recommended. The packages.config file is used in some project types to maintain the list of packages referenced by the project.

In general, we will not deliberately to keep a list in an excel file or others file to remember/keep track of which packages we will reuse in other projects. When we add a packages to the project by NuGet, NuGet will add a packages.config file to the project automatically. There are package ID, version, targetFramework options in that file, so we could use this file to remember/keep track of packages, for example:

```<code><?xml version="1.0" encoding="utf-8"?>
  <packages>
     <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net46" />
     <package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net46" developmentDependency="true" />
     <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net46" />
     <package id="Microsoft.Web.Xdt" version="2.1.1" targetFramework="net46" />
     <package id="Newtonsoft.Json" version="8.0.3" allowedVersions="(8,10]" targetFramework="net46" />
     <package id="NuGet.Core" version="2.11.1" targetFramework="net46" />

     <!--The following packages will be reused in many projects-->

     <package id="NuGet.Server" version="2.11.2" targetFramework="net46" />
     <package id="RouteMagic" version="1.3" targetFramework="net46" />
     <package id="WebActivatorEx" version="2.1.0" targetFramework="net46" />
  </packages>
</code>```

Note: You can also add comments in that file so that you can more easily find the useful info.

is there a way to have the same list of NuGet packages automatically installed into new solutions as you create them, without having to go through a list and install manually?

We could have the same list of NuGet packages automatically installed into new project not solution. Because NuGet team deprecated solution level packages in NuGet 3.0. So we could have the same list for new project by packages.config file.

You can copy the packages list in the packages.config file, add it into the packages.config of the new project, even you can just copy the packages.config file to the new project, then restore the packages and run the command line Update-Package -reinstall, after that, the new project will get the same packages list install.

Body:
does anyone have any advice to share on how you remember/keep track of which packages you will reuse in many projects?

Package.config should be recommended. The packages.config file is used in some project types to maintain the list of packages referenced by the project.

In general, we will not deliberately to keep a list in an excel file or others file to remember/keep track of which packages we will reuse in other projects. When we add a packages to the project by NuGet, NuGet will add a packages.config file to the project automatically. There are package ID, version, targetFramework options in that file, so we could use this file to remember/keep track of packages, for example:

<?xml version="1.0" encoding="utf-8"?>
  <packages>
     <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net46" />
     <package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net46" developmentDependency="true" />
     <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net46" />
     <package id="Microsoft.Web.Xdt" version="2.1.1" targetFramework="net46" />
     <package id="Newtonsoft.Json" version="8.0.3" allowedVersions="(8,10]" targetFramework="net46" />
     <package id="NuGet.Core" version="2.11.1" targetFramework="net46" />

     <!--The following packages will be reused in many projects-->

     <package id="NuGet.Server" version="2.11.2" targetFramework="net46" />
     <package id="RouteMagic" version="1.3" targetFramework="net46" />
     <package id="WebActivatorEx" version="2.1.0" targetFramework="net46" />
  </packages>

Note: You can also add comments in that file so that you can more easily find the useful info.

is there a way to have the same list of NuGet packages automatically installed into new solutions as you create them, without having to go through a list and install manually?

We could have the same list of NuGet packages automatically installed into new project not solution. Because NuGet team deprecated solution level packages in NuGet 3.0. So we could have the same list for new project by packages.config file.

You can copy the packages list in the packages.config file, add it into the packages.config of the new project, even you can just copy the packages.config file to the new project, then restore the packages and run the command line Update-Package -reinstall, after that, the new project will get the same packages list install.


问:
How to host a web service in MVC3?
How can I use a web service in mvc3? Where should I include the web service? Completely new to that...Help please.</p>

答:
In latest versions of VS you can click here:

In opened window you will be able to enter service address and do required configuration.

You can place your service references in any project. Id suggest to create a separate project and hold them there.

Title: How to host a web service in MVC3?


问:
ANTLR3 - Decision can match input using multiple alternatives
When running ANTLR3 on the following code, I get the message - warning(200): MYGRAMMAR.g:40:36: Decision can match input such as "QMARK" using multiple alternatives: 3, 4
As a result, alternative(s) 4 were disabled for that input.

The warning message is pointing me to postfixExpr. Is there a way to fix this?

```<code>grammar MYGRAMMAR;
options {language = C;}

tokens {
  BANG        = '!';
  COLON       = ':';
  FALSE_LITERAL = 'false';
  GREATER     = '>';
  LSHIFT      = '<<';
  MINUS       = '-';
  MINUS_MINUS = '--';
  PLUS        = '+';
  PLUS_PLUS   = '++';
  QMARK       = '?';
  QMARK_COLON = '?:';
  TILDE       = '~';
  TRUE_LITERAL = 'true';
}

condExpr
                    :  shiftExpr  (QMARK  condExpr COLON  condExpr)? ;

shiftExpr
                    :  addExpr  ( shiftOp   addExpr)* ;

addExpr
                    :  qmarkColonExpr  ( addOp  qmarkColonExpr)* ;

qmarkColonExpr
                    :  prefixExpr  ( QMARK_COLON  prefixExpr )? ;

prefixExpr
                    :  ( prefixOrUnaryMinus |  postfixExpr) ;

prefixOrUnaryMinus
                    :  prefixOp  prefixExpr ;

postfixExpr
                    :  primaryExpr ( postfixOp | BANG | QMARK )*;

primaryExpr
                    :   literal ;

shiftOp
                    :  ( LSHIFT  | rShift);

addOp
                    :  (PLUS  | MINUS);

prefixOp
                    :  ( BANG  | MINUS  | TILDE  | PLUS_PLUS  | MINUS_MINUS );

postfixOp
                    :  (PLUS_PLUS  | MINUS_MINUS);

rShift
                    :  (GREATER GREATER)=> a=GREATER b=GREATER {assertNoSpace($a,$b)}? ;

literal
                    :  ( TRUE_LITERAL  | FALSE_LITERAL );

assertNoSpace       [pANTLR3_COMMON_TOKEN t1, pANTLR3_COMMON_TOKEN t2]
                    : { $t1->line == $t2->line && $t1->getCharPositionInLine($t1) + 1 == $t2->getCharPositionInLine($t2) }? ;
</code>```

答:
I think one problem is that PLUS_PLUS as well as MINUS_MINUS will never be matched as they are defined after the respective PLUS or MINUS token. therefore the lexer will always output two PLUS tokens instead of one PLUS_PLUS token.

In order to avaoid something like this you have to define your PLUS_PLUS or MINUS_MINUS token before the PLUS or MINUS token as the lexer processes them in the order they are defined and won't look any further once it found a way to match the current input.

The same problem applies to QMARK_COLON as it is defined after QMARK (this only is a problem because there is another token type COLON to match the following colon).

See if fixing the ambiguities resolves the error message.

Body:
When running ANTLR3 on the following code, I get the message - warning(200): MYGRAMMAR.g:40:36: Decision can match input such as "QMARK" using multiple alternatives: 3, 4
As a result, alternative(s) 4 were disabled for that input.

The warning message is pointing me to postfixExpr. Is there a way to fix this?

grammar MYGRAMMAR;
options {language = C;}

tokens {
  BANG        = '!';
  COLON       = ':';
  FALSE_LITERAL = 'false';
  GREATER     = '>';
  LSHIFT      = '<<';
  MINUS       = '-';
  MINUS_MINUS = '--';
  PLUS        = '+';
  PLUS_PLUS   = '++';
  QMARK       = '?';
  QMARK_COLON = '?:';
  TILDE       = '~';
  TRUE_LITERAL = 'true';
}

condExpr
                    :  shiftExpr  (QMARK  condExpr COLON  condExpr)? ;

shiftExpr
                    :  addExpr  ( shiftOp   addExpr)* ;

addExpr
                    :  qmarkColonExpr  ( addOp  qmarkColonExpr)* ;

qmarkColonExpr
                    :  prefixExpr  ( QMARK_COLON  prefixExpr )? ;

prefixExpr
                    :  ( prefixOrUnaryMinus |  postfixExpr) ;

prefixOrUnaryMinus
                    :  prefixOp  prefixExpr ;

postfixExpr
                    :  primaryExpr ( postfixOp | BANG | QMARK )*;

primaryExpr
                    :   literal ;

shiftOp
                    :  ( LSHIFT  | rShift);

addOp
                    :  (PLUS  | MINUS);

prefixOp
                    :  ( BANG  | MINUS  | TILDE  | PLUS_PLUS  | MINUS_MINUS );

postfixOp
                    :  (PLUS_PLUS  | MINUS_MINUS);

rShift
                    :  (GREATER GREATER)=> a=GREATER b=GREATER {assertNoSpace($a,$b)}? ;

literal
                    :  ( TRUE_LITERAL  | FALSE_LITERAL );

assertNoSpace       [pANTLR3_COMMON_TOKEN t1, pANTLR3_COMMON_TOKEN t2]
                    : { $t1->line == $t2->line && $t1->getCharPositionInLine($t1) + 1 == $t2->getCharPositionInLine($t2) }? ;


问:
Dropdown List with a relationship table attribute [MVC .NET]
Since English is not my native language, I'm very sorry for any mistake I will exihbit in the next senteces.

I created a database with products (produtos) and types of Products (Categoria)

My objective was to create a relationship (codefirst) in MVC from One to Many.
Where a type of product (Categoria) can have multiple Products (Produtos)

So I had created this:

```<code>namespace HardwareWarehouse.Models
{
    public class Produto
    {
        public Produto()
        {

        }
        [Key]
        public int IDProduto { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        [Required]
        public double Preco { get; set; }

        [Required]
        public double Peso { get; set; }

        [Required]
        [StringLength(255)]
        public string Descricao { get; set; }

        public int Imagem { get; set; }

        public DateTime UltimaAtualizacao { get; set; }

        public int Stock { get; set; }

        public int CategoriaID { get; set; }

        public virtual Produto Produtos { get; set; }
    }
}
</code>```

And for the Category/type of Product (Categoria), I created this..

```<code>namespace HardwareWarehouse.Models
{
    public class Categoria
    {
        public Categoria()
        {
            Produtos = new List<Produto>();
        }
        [Key]
        public int CategoriaID { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        public virtual ICollection<Produto> Produtos { get; set; }
    }
}
</code>```

So I think my relationship between both tables are fine so far.

Next, I had created a controller, and used a default view to store some data.
Which looks like this:

And this is my default view that shows that info..

```<code>@model IEnumerable<HardwareWarehouse.Models.Produto>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Nome)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Preco)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Peso)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Descricao)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Imagem)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UltimaAtualizacao)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Stock)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CategoriaID)
            </th>
            <th></th>
        </tr>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Nome)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Preco)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Peso)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Descricao)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Imagem)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UltimaAtualizacao)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Stock)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CategoriaID)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.IDProduto }) |
                @Html.ActionLink("Details", "Details", new { id=item.IDProduto }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.IDProduto })
            </td>
        </tr>
    }

    </table>
</body>
</html>
</code>```

The Millions dollar question is?
How do I make the view to show the Categoria.Nome instead of the CategoriaID number on that view?

Thanks in advance..

答:
Adding to Alisson answer, ViewModels are used to send multiple models to the view
Here is the Link
ViewModel in ASP.NET MVC</p>

Body:
Since English is not my native language, I'm very sorry for any mistake I will exihbit in the next senteces.

I created a database with products (produtos) and types of Products (Categoria)

My objective was to create a relationship (codefirst) in MVC from One to Many.
Where a type of product (Categoria) can have multiple Products (Produtos)

So I had created this:

namespace HardwareWarehouse.Models
{
    public class Produto
    {
        public Produto()
        {

        }
        [Key]
        public int IDProduto { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        [Required]
        public double Preco { get; set; }

        [Required]
        public double Peso { get; set; }

        [Required]
        [StringLength(255)]
        public string Descricao { get; set; }

        public int Imagem { get; set; }

        public DateTime UltimaAtualizacao { get; set; }

        public int Stock { get; set; }

        public int CategoriaID { get; set; }

        public virtual Produto Produtos { get; set; }
    }
}

And for the Category/type of Product (Categoria), I created this..

namespace HardwareWarehouse.Models
{
    public class Categoria
    {
        public Categoria()
        {
            Produtos = new List<Produto>();
        }
        [Key]
        public int CategoriaID { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        public virtual ICollection<Produto> Produtos { get; set; }
    }
}

So I think my relationship between both tables are fine so far.

Next, I had created a controller, and used a default view to store some data.
Which looks like this:

And this is my default view that shows that info..

@model IEnumerable<HardwareWarehouse.Models.Produto>

@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

        @Html.ActionLink("Create New", "Create")

                @Html.DisplayNameFor(model => model.Nome)

                @Html.DisplayNameFor(model => model.Preco)

                @Html.DisplayNameFor(model => model.Peso)

                @Html.DisplayNameFor(model => model.Descricao)

                @Html.DisplayNameFor(model => model.Imagem)

                @Html.DisplayNameFor(model => model.UltimaAtualizacao)

                @Html.DisplayNameFor(model => model.Stock)

                @Html.DisplayNameFor(model => model.CategoriaID)

    @foreach (var item in Model) {

                @Html.DisplayFor(modelItem => item.Nome)

                @Html.DisplayFor(modelItem => item.Preco)

                @Html.DisplayFor(modelItem => item.Peso)

                @Html.DisplayFor(modelItem => item.Descricao)

                @Html.DisplayFor(modelItem => item.Imagem)

                @Html.DisplayFor(modelItem => item.UltimaAtualizacao)

                @Html.DisplayFor(modelItem => item.Stock)

                @Html.DisplayFor(modelItem => item.CategoriaID)

                @Html.ActionLink("Edit", "Edit", new { id=item.IDProduto }) |
                @Html.ActionLink("Details", "Details", new { id=item.IDProduto }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.IDProduto })

    }

The Millions dollar question is?
How do I make the view to show the Categoria.Nome instead of the CategoriaID number on that view?

Thanks in advance..


问:
Table inside a div - horizontal scrollbar only at the bottom of the div
I have a big table inside a div that has a overflow-auto defined. Still I can get only a vertical scrollbar visible. The horizontal scrollbar is at the bottom at the div, which makes it quite inconvenient to use. Any ideas what is happening here?!</p>

答:
How about something like this?

$("#scrollbar").on("scroll", function(){
  var container = $("#container");
  var scrollbar = $("#scrollbar");

  ScrollUpdate(container, scrollbar);
});

function ScrollUpdate(content, scrollbar){
    $("#spacer").css({"width":"500px"}); // set the spacer width
    scrollbar.width = content.width() + "px";
    content.scrollLeft(scrollbar.scrollLeft());
}

ScrollUpdate($("#container"),$("#scrollbar"));

$("#tab").tableHeadFixer({
  "left": 1,
  "right": 0,
  "head": true
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
  width: 300px;
  height: 300px;
  background: green;
  overflow-x: hidden !important;
  overflow-y: auto;
  position: absolute;
  left: 0px;
  top: 0px;
}

#scrollbar {
  position: fixed;
  left: 0px;
  bottom: 0px;
  width: 300px;
  overflow-x: scroll;
  overflow-y: hidden;
  z-index: 10;
}

#spacer {
  height: 1px;
}

#tab {
  width: 500px;
  height: 500px;
  background: #CCCCCC;
}

tr,td {
  border: 1px solid black;
}</code>```

     Title
     Name
     History

     test
     test
     test

     test
     test
     test

     test
     test
     test

     test
     test
     test

```

Body:
How about something like this?

$("#scrollbar").on("scroll", function(){
  var container = $("#container");
  var scrollbar = $("#scrollbar");

  ScrollUpdate(container, scrollbar);
});

function ScrollUpdate(content, scrollbar){
    $("#spacer").css({"width":"500px"}); // set the spacer width
    scrollbar.width = content.width() + "px";
    content.scrollLeft(scrollbar.scrollLeft());
}

ScrollUpdate($("#container"),$("#scrollbar"));

$("#tab").tableHeadFixer({
  "left": 1,
  "right": 0,
  "head": true
});

#container {
  width: 300px;
  height: 300px;
  background: green;
  overflow-x: hidden !important;
  overflow-y: auto;
  position: absolute;
  left: 0px;
  top: 0px;
}

#scrollbar {
  position: fixed;
  left: 0px;
  bottom: 0px;
  width: 300px;
  overflow-x: scroll;
  overflow-y: hidden;
  z-index: 10;
}

#spacer {
  height: 1px;
}

#tab {
  width: 500px;
  height: 500px;
  background: #CCCCCC;
}

tr,td {
  border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>

<div id="scrollbar"><div id="spacer"></div></div>

<div id="container">
  <table id="tab">
    <thead>
    <tr>
     <th>Title</th>
     <th>Name</th>
     <th>History</th>
    </tr>
   </thead>
   <tbody>
    <tr>
     <td>test</td>
     <td>test</td>
     <td>test</td>
    </tr>
    <tr>
     <td>test</td>
     <td>test</td>
     <td>test</td>
    </tr>
    <tr>
     <td>test</td>
     <td>test</td>
     <td>test</td>
    </tr>
    <tr>
     <td>test</td>
     <td>test</td>
     <td>test</td>
    </tr>
   </tbody>
  </table>
</div>


问:
window.open("url","_self") works well on localhost url, but not when I put it on a server
I have an angularJS frontend that I redirect to a third party payment gateway when a customer clicks on the Pay button.

I am currently using the following function to redirect to the payment gateway:

```<code>if(status.data.result == "true"){
var ref = window.open(url,'_self');
}
};
</code>```

This code works well when I try it on localhost. But does not work when I put it on the ubuntu server.

Any ideas on why?

Regards,
Galeej

答:
May be your content security policy is blocking this url to load.
You can try using _blank instead of _self to see if that is the case.
Also it would be better to use $window, because angular.

Also are you using the fully qualified URL ?

Body:
I have an angularJS frontend that I redirect to a third party payment gateway when a customer clicks on the Pay button.

I am currently using the following function to redirect to the payment gateway:

if(status.data.result == "true"){
var ref = window.open(url,'_self');
}
};

This code works well when I try it on localhost. But does not work when I put it on the ubuntu server.

Any ideas on why?

Regards,
Galeej


问:
Spring: automatic rollback on checked exceptions
One way to configure Spring to rollback on a non RuntimeExceptions is using @Transactional(rollbackFor=...) annotation on the service classes. The problem with this approach is that we need to define (rollbackFor=...) for almost all the service classes which seems really redundant.

My question: Is there any way to configure a default behaviour for Spring transaction manager to rollback on a non RuntimeException whenever it happens without declaring it on every @Transactional annotation. Something like using @ApplicationException(rollback=true) annotation on an exception class in EJB.

答:
You can't do it for application level with @Transactional , but you can :

variant 1 : extend @Transactional annotation and put it as default value for rollbackfor. But set rollbackFor unchecked exceptions only that you need .With this you  can control rollbacks only for case that you sure , and avoid copy past of @Transactional(rollbackFor =MyCheckedException.class)

Like:

```<code>@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(rollbackFor=MyCheckedException.class)
public @interface TransactionalWithRollback {
}
</code>```

And use this annotation instead of standard  @Transactional.

variant 2 : you can create extension from AnnotationTransactionAttributeSource and override  method determineTransactionAttribute:

```<code>protected TransactionAttribute  determineTransactionAttribute(AnnotatedElement ae)
//Determine the transaction attribute for the given method or class.
</code>```

TransactionAttribute see TransactionAttribute api , there is a method

boolean    rollbackOn(Throwable ex) Should we roll back on the given exception?

```<code>protected TransactionAttribute determineTransactionAttribute(
    AnnotatedElement ae) {
    return new DelegatingTransactionAttribute(target) {
        @Override
        public boolean rollbackOn(Throwable ex) {
           return (check is exception type as you need for rollback );
       }
};
</code>```

}

Second approach is not so good as first as you do it really global for transaction manager. Better use custom annotation as you can control it any apply only for methods/classes where you really need it. But if you need it in any case use second variant , it will be your default transnational behavior.

Body:
You can't do it for application level with @Transactional , but you can :

variant 1 : extend @Transactional annotation and put it as default value for rollbackfor. But set rollbackFor unchecked exceptions only that you need .With this you  can control rollbacks only for case that you sure , and avoid copy past of @Transactional(rollbackFor =MyCheckedException.class)

Like:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(rollbackFor=MyCheckedException.class)
public @interface TransactionalWithRollback {
}

And use this annotation instead of standard  @Transactional.

variant 2 : you can create extension from AnnotationTransactionAttributeSource and override  method determineTransactionAttribute:

protected TransactionAttribute  determineTransactionAttribute(AnnotatedElement ae)
//Determine the transaction attribute for the given method or class.

TransactionAttribute see TransactionAttribute api , there is a method

boolean    rollbackOn(Throwable ex) Should we roll back on the given exception?

protected TransactionAttribute determineTransactionAttribute(
    AnnotatedElement ae) {
    return new DelegatingTransactionAttribute(target) {
        @Override
        public boolean rollbackOn(Throwable ex) {
           return (check is exception type as you need for rollback );
       }
};

}

Second approach is not so good as first as you do it really global for transaction manager. Better use custom annotation as you can control it any apply only for methods/classes where you really need it. But if you need it in any case use second variant , it will be your default transnational behavior.


问:
c# mvc form: how to build view for simple feedback form leveraging the benefit of using html.editorfor?
I have simple input form (basically for feedback) with following fields:
Name, Gender, Mobile-Number, Complaint text. (To simplify I am not mentioning any POST action OR submit button on the form)

Currently, I have created following MVC structure:

```<code>public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
       return View(); //This view displays the complaint form with all above fields
    }
}
</code>```

I read this and several other links where they suggest to use @Html.EditorFor as it creates UI based on model data-type.

Currently, I am not passing any model to the [HttpGet] view. If I want to use @Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? What is best pratise to create such MVC forms?

答:
If you want to use  @Html.EditorFor, then you mast pass the model to the view.What does @Html.EditorFor do? It makes the html tag like

```<code><input class="text-box single-line" id="Name" name="Name" type="text" value="">
</code>```

So if you do not want to pass the model to the view then you need to write the raw html tag like above. It is important to keep the html tag's name property same as  the mvc's model property because when you want to post the data to the controller the name property of the html tag will map the mvc model property and get the corresponding value at the Controller method.

At the view(somthing.cshtml) you can use html tags, because .cshtml==.cs+html   . So the whole code look like

Controller methods

```<code> public ActionResult FeedBack()
 {
     return View();
 }

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FeedBack(FeedBackModel Model)
{
    var feedBack = Model;
     return View();
 }
</code>```

And the View

```<code><form action="/Home/FeedBack" method="post" id="feedBackForm">
    @Html.AntiForgeryToken()
    <hr>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Name</label>
        </div>
        <div class="col-md-5">
            <input class="text-box single-line" name="Name" type="text">
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Gender</label>
        </div>
        <div class="col-md-5">
            <select name="Gender">
                <option value="male">Male</option>
                <option value="female">Female</option>
            </select>
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">MobileNumber</label>
        </div>
        <div class="col-md-5">
            <input class="text-box single-line" name="MobileNumber" type="text">
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Complaint</label>
        </div>
        <div class="col-md-5">
            <textarea class="text-box single-line" name="Complaint"></textarea>
        </div>
        </div>

    <div class="col-md-5">
        <input type="submit" value="Create" class="btn btn-default">
    </div>
</form>
</code>```

If you do not want to use submit then you can use ajax.

Body:
I have simple input form (basically for feedback) with following fields:
Name, Gender, Mobile-Number, Complaint text. (To simplify I am not mentioning any POST action OR submit button on the form)

Currently, I have created following MVC structure:

public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
       return View(); //This view displays the complaint form with all above fields
    }
}

I read this and several other links where they suggest to use @Html.EditorFor as it creates UI based on model data-type.

Currently, I am not passing any model to the [HttpGet] view. If I want to use @Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? What is best pratise to create such MVC forms?

Body:
If you want to use  @Html.EditorFor, then you mast pass the model to the view.What does @Html.EditorFor do? It makes the html tag like

<input class="text-box single-line" id="Name" name="Name" type="text" value="">

So if you do not want to pass the model to the view then you need to write the raw html tag like above. It is important to keep the html tag's name property same as  the mvc's model property because when you want to post the data to the controller the name property of the html tag will map the mvc model property and get the corresponding value at the Controller method.

At the view(somthing.cshtml) you can use html tags, because .cshtml==.cs+html   . So the whole code look like

Controller methods

 public ActionResult FeedBack()
 {
     return View();
 }

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FeedBack(FeedBackModel Model)
{
    var feedBack = Model;
     return View();
 }

And the View

<form action="/Home/FeedBack" method="post" id="feedBackForm">
    @Html.AntiForgeryToken()
    <hr>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Name</label>
        </div>
        <div class="col-md-5">
            <input class="text-box single-line" name="Name" type="text">
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Gender</label>
        </div>
        <div class="col-md-5">
            <select name="Gender">
                <option value="male">Male</option>
                <option value="female">Female</option>
            </select>
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">MobileNumber</label>
        </div>
        <div class="col-md-5">
            <input class="text-box single-line" name="MobileNumber" type="text">
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Complaint</label>
        </div>
        <div class="col-md-5">
            <textarea class="text-box single-line" name="Complaint"></textarea>
        </div>
        </div>

    <div class="col-md-5">
        <input type="submit" value="Create" class="btn btn-default">
    </div>
</form>

If you do not want to use submit then you can use ajax.


问:
Given an even number ( greater than 2 ), return two prime numbers whose sum will be equal to given number
```<code>vector<int> Solution::primesum(int n) {
  int prime[n+1];
  for(int i=0;i<n+1;i++){
    prime[i]=1;
  }
   prime[0]=0;
   prime[1]=0;
   for(int i=2;i<=sqrt(n);i++){

        if(prime[i]==1){
            for(int j=2;i*j<=n;j++)
               prime[i*j]=0;
        }

  }
  vector <int> sum;
  for(int i=2;i<=(n)/2;i++){
      if(prime[i]==1&&prime[n-i]==1){
       sum.push_back(i);
       sum.push_back(n-i);
       return sum;
      }
      }
    return sum;
     }
</code>```

The above code is working fine for smaller inputs but when I try to provide it with numbers something like >100000000, it is showing segmentation fault.Can someone please help me? Thanks!

答: Most likely int prime[n+1] leads to a stackoverflow (100'000'000 requires ~400 MB on the stack). I'd recommend using std::vector<int> prime(n+1) instead.

Body:
vector<int> Solution::primesum(int n) {
  int prime[n+1];
  for(int i=0;i<n+1;i++){
    prime[i]=1;
  }
   prime[0]=0;
   prime[1]=0;
   for(int i=2;i<=sqrt(n);i++){

        if(prime[i]==1){
            for(int j=2;i*j<=n;j++)
               prime[i*j]=0;
        }

  }
  vector <int> sum;
  for(int i=2;i<=(n)/2;i++){
      if(prime[i]==1&&prime[n-i]==1){
       sum.push_back(i);
       sum.push_back(n-i);
       return sum;
      }
      }
    return sum;
     }

The above code is working fine for smaller inputs but when I try to provide it with numbers something like >100000000, it is showing segmentation fault.Can someone please help me? Thanks!